azzenn4 commited on
Commit
1908732
·
1 Parent(s): 2839e12
Files changed (3) hide show
  1. inspect_timor.py +42 -39
  2. process_patches.py +207 -0
  3. statistics.py +116 -0
inspect_timor.py CHANGED
@@ -2,8 +2,9 @@ import os
2
  import rasterio
3
  import matplotlib.pyplot as plt
4
  import numpy as np
 
 
5
 
6
- data_root = "./datasets/Timor_Ml4Floods"
7
 
8
  def check_ground_truth(gt_file):
9
  with rasterio.open(gt_file) as src:
@@ -72,48 +73,50 @@ def visualize_ground_truth(gt_file):
72
  plt.show()
73
 
74
 
75
- def get_gt():
76
 
77
- ground_truth = f"{data_root}/GT"
78
-
79
- timor_data_dir = [
80
- f"{ground_truth}/EMSR507_AOI01_DEL_PRODUCT", # <- Pleiades-1A-1B
81
- f"{ground_truth}/EMSR507_AOI02_DEL_PRODUCT", # <- PlanetScope
82
- f"{ground_truth}/EMSR507_AOI03_DEL_PRODUCT", # <- PlanetScope
83
- f"{ground_truth}/EMSR507_AOI05_DEL_PRODUCT", # <- Sentinel-2
84
- f"{ground_truth}/EMSR507_AOI07_GRA_PRODUCT" # <- PlanetScope
 
 
 
 
 
85
  ]
86
- O1_incl = f"{timor_data_dir[0]}/include.txt"
87
- O2_incl = f"{timor_data_dir[1]}/include.txt"
88
- O3_incl = f"{timor_data_dir[2]}/include.txt"
89
- O5_incl = f"{timor_data_dir[3]}/include.txt"
90
- O7_incl = f"{timor_data_dir[4]}/include.txt"
91
-
92
- def read_include(path):
93
  if not os.path.exists(path):
94
  return []
95
  with open(path, 'r') as file:
96
  return [line.strip() for line in file if line.strip()]
97
-
98
- AOIO1 = read_include(O1_incl)
99
- AOIO2 = read_include(O2_incl)
100
- AOIO3 = read_include(O3_incl)
101
- AOIO5 = read_include(O5_incl)
102
- AOIO7 = read_include(O7_incl)
103
-
104
- tif01_gt = [f"{timor_data_dir[0]}/EMSR507_AOI01_DEL_PRODUCT_{i}.tif" for i in AOIO1]
105
- tif02_gt = [f"{timor_data_dir[1]}/EMSR507_AOI02_DEL_PRODUCT_{i}.tif" for i in AOIO2]
106
- tif03_gt = [f"{timor_data_dir[2]}/EMSR507_AOI03_DEL_PRODUCT_{i}.tif" for i in AOIO3]
107
- tif05_gt = [f"{timor_data_dir[3]}/EMSR507_AOI05_DEL_PRODUCT_{i}.tif" for i in AOIO5]
108
- tif07_gt = [f"{timor_data_dir[4]}/EMSR507_AOI07_GRA_PRODUCT_{i}.tif" for i in AOIO7]
109
-
110
- return {
111
- "tif01_gt": tif01_gt,
112
- "tif02_gt": tif02_gt,
113
- "tif03_gt": tif03_gt,
114
- "tif05_gt": tif05_gt,
115
- "tif07_gt": tif07_gt
116
- }
 
117
 
118
  SATELLITE_MAP = {
119
  "tif01_s2": "pleiades",
@@ -125,7 +128,7 @@ SATELLITE_MAP = {
125
 
126
  def plot_all_gt_with_labels():
127
 
128
- gt_dict = get_gt()
129
 
130
  for key, file_list in gt_dict.items():
131
 
@@ -172,9 +175,9 @@ def plot_all_gt_with_labels():
172
  plt.tight_layout()
173
  plt.show()
174
 
175
-
176
  plot_all_gt_with_labels()
177
 
 
178
 
179
 
180
 
 
2
  import rasterio
3
  import matplotlib.pyplot as plt
4
  import numpy as np
5
+
6
+ USED_BANDS = (1,2,3,8,11,12)
7
 
 
8
 
9
  def check_ground_truth(gt_file):
10
  with rasterio.open(gt_file) as src:
 
73
  plt.show()
74
 
75
 
76
+ def get_category(use: str, data_root: str):
77
 
78
+ if use == 'gt':
79
+ data_dir = f"{data_root}/GT"
80
+ elif use == 's2':
81
+ data_dir = f"{data_root}/S2"
82
+ else:
83
+ raise ValueError(f"Invalid use type: {use}. Must be 'gt' or 's2'")
84
+
85
+ aoi_configs = [
86
+ ("AOI01", "DEL", "pleiades"),
87
+ ("AOI02", "DEL", "planet"),
88
+ ("AOI03", "DEL", "planet"),
89
+ ("AOI05", "DEL", "sentinel2"),
90
+ ("AOI07", "GRA", "planet"),
91
  ]
92
+
93
+ def read_include(path: str) -> list[str]:
94
+
 
 
 
 
95
  if not os.path.exists(path):
96
  return []
97
  with open(path, 'r') as file:
98
  return [line.strip() for line in file if line.strip()]
99
+
100
+ result = {}
101
+
102
+ for aoi_id, product_type, satellite in aoi_configs:
103
+ aoi_num = aoi_id[-2:] # Extract "01", "02", etc.
104
+
105
+ aoi_dir = f"{data_dir}/EMSR507_{aoi_id}_{product_type}_PRODUCT"
106
+ include_path = f"{aoi_dir}/include.txt"
107
+
108
+ include_items = read_include(include_path)
109
+
110
+ tif_files = [
111
+ f"{aoi_dir}/EMSR507_{aoi_id}_{product_type}_PRODUCT_{item}.tif"
112
+ for item in include_items
113
+ ]
114
+
115
+
116
+ key = f"tif{aoi_num}_{'gt' if use == 'gt' else 's2'}"
117
+ result[key] = tif_files
118
+
119
+ return result
120
 
121
  SATELLITE_MAP = {
122
  "tif01_s2": "pleiades",
 
128
 
129
  def plot_all_gt_with_labels():
130
 
131
+ gt_dict = get_category(use='s2', data_root='./datasets/Timor_ML4FLood')
132
 
133
  for key, file_list in gt_dict.items():
134
 
 
175
  plt.tight_layout()
176
  plt.show()
177
 
 
178
  plot_all_gt_with_labels()
179
 
180
+
181
 
182
 
183
 
process_patches.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import rasterio
3
+ from PIL import Image, ImageDraw, ImageFont
4
+ import os
5
+ import numpy as np
6
+
7
+ class InMemoryDataset(torch.utils.data.Dataset):
8
+ def __init__(self, data_list, preprocess_func):
9
+ self.data_list = data_list
10
+ self.preprocess_func = preprocess_func
11
+
12
+ def __getitem__(self, i):
13
+ return self.preprocess_func(self.data_list[i])
14
+
15
+ def __len__(self):
16
+ return len(self.data_list)
17
+
18
+ INPUT_SIZE = 224
19
+ PATCH_SIZE = 224
20
+ STRIDE = 224
21
+
22
+ root = 'datasets/WorldFloodsv2'
23
+ test_path_s2 = f'{root}/train/S2/'
24
+ test_path_labels = f'{root}/train/gt/'
25
+
26
+
27
+ extension = '.tif'
28
+
29
+ timor_leste_events = {
30
+ "EMSR507_AOI01_DEL_PRODUCT": "Pleiades-1A-1B",
31
+ "EMSR507_AOI02_DEL_PRODUCT": "PlanetScope",
32
+ "EMSR507_AOI03_DEL_PRODUCT": "PlanetScope",
33
+ "EMSR507_AOI05_DEL_PRODUCT": "Sentinel-2",
34
+ "EMSR507_AOI07_GRA_PRODUCT": "PlanetScope"
35
+ }
36
+
37
+ files_s2 = [(f"{test_path_s2}{event_id}{extension}", satellite)
38
+ for event_id, satellite in timor_leste_events.items()]
39
+
40
+ files_gt = [(f"{test_path_labels}{event_id}{extension}", satellite)
41
+ for event_id, satellite in timor_leste_events.items()]
42
+
43
+
44
+ output_root_s2 = "./datasets/Timor_Processed/S2"
45
+ os.makedirs(output_root_s2, exist_ok=True)
46
+
47
+ output_root_gt = "./datasets/Timor_Processed/GT"
48
+ os.makedirs(output_root_gt, exist_ok=True)
49
+
50
+ output_root_floodmask = "./datasets/Timor_Processed/Floodmask"
51
+ os.makedirs(output_root_gt, exist_ok=True)
52
+
53
+ def sliding_window_crop(image, window_size=PATCH_SIZE, stride=STRIDE):
54
+ C, H, W = image.shape
55
+ patches = []
56
+ for y in range(0, H, stride):
57
+ for x in range(0, W, stride):
58
+ y_end = min(y + window_size, H)
59
+ x_end = min(x + window_size, W)
60
+ y_start = max(y_end - window_size, 0)
61
+ x_start = max(x_end - window_size, 0)
62
+ patch = image[:, y_start:y_end, x_start:x_end]
63
+ patches.append(patch)
64
+ return patches
65
+
66
+
67
+ def read_tif_as_tensor(tif_path):
68
+ with rasterio.open(tif_path) as src:
69
+ img = src.read() # shape: (bands, H, W)
70
+ img = torch.from_numpy(img).float()
71
+ return img
72
+
73
+
74
+ def save_patch_as_tif(patch_tensor, output_path):
75
+ patch_np = patch_tensor.numpy()
76
+ with rasterio.open(
77
+ output_path,
78
+ 'w',
79
+ driver='GTiff',
80
+ height=patch_np.shape[1],
81
+ width=patch_np.shape[2],
82
+ count=patch_np.shape[0],
83
+ dtype=patch_np.dtype
84
+ ) as dst:
85
+ dst.write(patch_np)
86
+
87
+
88
+ def plot_patches(patches, cols=5, save_path=None, is_label=False):
89
+ rows = (len(patches) + cols - 1) // cols
90
+ patch_images = []
91
+ font = ImageFont.load_default()
92
+
93
+ for idx, patch in enumerate(patches):
94
+ if is_label:
95
+ # Labels assumed to be single-channel
96
+ patch_np = patch[0].numpy()
97
+ patch_np = ((patch_np - patch_np.min()) / (patch_np.max() - patch_np.min() + 1e-8) * 255).astype(np.uint8)
98
+ img = Image.fromarray(patch_np).convert("L")
99
+ else:
100
+ # RGB visualization for images
101
+ patch_np = patch[:3].numpy()
102
+ patch_np = (patch_np - patch_np.min()) / (patch_np.max() - patch_np.min() + 1e-8) * 255
103
+ patch_np = patch_np.transpose(1,2,0).astype(np.uint8)
104
+ img = Image.fromarray(patch_np)
105
+ draw = ImageDraw.Draw(img)
106
+ draw.text((5,5), str(idx), fill=(255,0,0), font=font)
107
+ patch_images.append(img)
108
+
109
+ width, height = patch_images[0].size
110
+ grid_img = Image.new('RGB' if not is_label else 'L', (cols * width, rows * height), color=(255,255,255) if not is_label else 255)
111
+ for i, img in enumerate(patch_images):
112
+ row = i // cols
113
+ col = i % cols
114
+ grid_img.paste(img, (col*width, row*height))
115
+
116
+ if save_path:
117
+ grid_img.save(save_path)
118
+
119
+ # Class color map: 0=invalid, 1=land, 2=flood, 3=permanent water
120
+ CLASS_COLORS = {
121
+ 0: (0, 0, 0), # black for invalid/no data
122
+ 1: (34, 139, 34), # green for flood (gt)
123
+ 2: (0, 0, 255), # blue for cloud (gt)
124
+ }
125
+
126
+ def plot_label_patches(label_patches, cols=5, save_path=None):
127
+ rows = (len(label_patches) + cols - 1) // cols
128
+ patch_images = []
129
+ font = ImageFont.load_default()
130
+
131
+ for idx, patch in enumerate(label_patches):
132
+ patch_np = patch[0].numpy().astype(int) # assume single channel
133
+ H, W = patch_np.shape
134
+ color_img = np.zeros((H, W, 3), dtype=np.uint8)
135
+ for cls, color in CLASS_COLORS.items():
136
+ color_img[patch_np == cls] = color
137
+ img = Image.fromarray(color_img)
138
+ draw = ImageDraw.Draw(img)
139
+ draw.text((5,5), str(idx), fill=(255,0,0), font=font)
140
+ patch_images.append(img)
141
+
142
+ width, height = patch_images[0].size
143
+ grid_img = Image.new('RGB', (cols * width, rows * height), color=(255,255,255))
144
+ for i, img in enumerate(patch_images):
145
+ row = i // cols
146
+ col = i % cols
147
+ grid_img.paste(img, (col*width, row*height))
148
+
149
+ if save_path:
150
+ grid_img.save(save_path)
151
+
152
+
153
+ # Main processing loop
154
+ for tif_path, satellite in files_s2:
155
+ print(f"Processing {tif_path} ({satellite})...")
156
+ img_tensor = read_tif_as_tensor(tif_path)
157
+ patches = sliding_window_crop(img_tensor, PATCH_SIZE, STRIDE)
158
+
159
+ base_name = os.path.splitext(os.path.basename(tif_path))[0]
160
+ patch_output_dir = os.path.join(output_root_s2, base_name)
161
+ os.makedirs(patch_output_dir, exist_ok=True)
162
+
163
+ # Save image patches
164
+ for idx, patch in enumerate(patches):
165
+ patch_name = f"{base_name}_{idx}.tif"
166
+ save_patch_as_tif(patch, os.path.join(patch_output_dir, patch_name))
167
+
168
+ # # Plot image patches
169
+ # plot_save_path = os.path.join(patch_output_dir, f"{base_name}_grid.png")
170
+ # plot_patches(patches, save_path=plot_save_path)
171
+
172
+ # # If labels exist in a corresponding folder
173
+ # label_path = tif_path.replace('/S2/', '/gt/') # assuming label folder structure
174
+ # if os.path.exists(label_path):
175
+ # label_tensor = read_tif_as_tensor(label_path)
176
+ # label_patches = sliding_window_crop(label_tensor, PATCH_SIZE, STRIDE)
177
+ # plot_label_path = os.path.join(patch_output_dir, f"{base_name}_labels_grid.png")
178
+ # plot_label_patches(label_patches, save_path=plot_label_path)
179
+
180
+
181
+ # Main processing loop
182
+ for tif_path, satellite in files_gt:
183
+ print(f"Processing {tif_path} ({satellite})...")
184
+ img_tensor = read_tif_as_tensor(tif_path)
185
+ patches = sliding_window_crop(img_tensor, PATCH_SIZE, STRIDE)
186
+
187
+ base_name = os.path.splitext(os.path.basename(tif_path))[0]
188
+ patch_output_dir = os.path.join(output_root_gt, base_name)
189
+ os.makedirs(patch_output_dir, exist_ok=True)
190
+
191
+ # Save image patches
192
+ for idx, patch in enumerate(patches):
193
+ patch_name = f"{base_name}_{idx}.tif"
194
+ save_patch_as_tif(patch, os.path.join(patch_output_dir, patch_name))
195
+
196
+ # # Plot image patches
197
+ # plot_save_path = os.path.join(patch_output_dir, f"{base_name}_grid.png")
198
+ # plot_patches(patches, save_path=plot_save_path)
199
+
200
+ # # If labels exist in a corresponding folder
201
+ # label_path = tif_path.replace('/S2/', '/gt/') # assuming label folder structure
202
+ # if os.path.exists(label_path):
203
+ # label_tensor = read_tif_as_tensor(label_path)
204
+ # label_patches = sliding_window_crop(label_tensor, PATCH_SIZE, STRIDE)
205
+ # plot_label_path = os.path.join(patch_output_dir, f"{base_name}_labels_grid.png")
206
+ # plot_label_patches(label_patches, save_path=plot_label_path)
207
+
statistics.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import rasterio
3
+ import numpy as np
4
+ from tqdm import tqdm
5
+
6
+ USED_BANDS = (1, 2, 3, 8, 11, 12)
7
+
8
+ def get_category(use: str, data_root: str):
9
+ """Get file paths for specified data type"""
10
+ if use == 'gt':
11
+ data_dir = f"{data_root}/GT"
12
+ elif use == 's2':
13
+ data_dir = f"{data_root}/S2"
14
+ else:
15
+ raise ValueError(f"Invalid use type: {use}. Must be 'gt' or 's2'")
16
+
17
+ aoi_configs = [
18
+ ("AOI01", "DEL", "pleiades"),
19
+ ("AOI02", "DEL", "planet"),
20
+ ("AOI03", "DEL", "planet"),
21
+ ("AOI05", "DEL", "sentinel2"),
22
+ ("AOI07", "GRA", "planet"),
23
+ ]
24
+
25
+ def read_include(path: str) -> list[str]:
26
+ if not os.path.exists(path):
27
+ return []
28
+ with open(path, 'r') as file:
29
+ return [line.strip() for line in file if line.strip()]
30
+
31
+ result = {}
32
+
33
+ for aoi_id, product_type, satellite in aoi_configs:
34
+ aoi_num = aoi_id[-2:]
35
+ aoi_dir = f"{data_dir}/EMSR507_{aoi_id}_{product_type}_PRODUCT"
36
+ include_path = f"{aoi_dir}/include.txt"
37
+ include_items = read_include(include_path)
38
+ tif_files = [
39
+ f"{aoi_dir}/EMSR507_{aoi_id}_{product_type}_PRODUCT_{item}.tif"
40
+ for item in include_items
41
+ ]
42
+ key = f"tif{aoi_num}_{'gt' if use == 'gt' else 's2'}"
43
+ result[key] = tif_files
44
+
45
+ return result
46
+
47
+
48
+ def calculate_s2_statistics(data_root: str, used_bands=USED_BANDS):
49
+
50
+ print("Getting S2 file paths...")
51
+ s2_dict = get_category(use='s2', data_root=data_root)
52
+
53
+ all_files = []
54
+ for key, file_list in s2_dict.items():
55
+ all_files.extend(file_list)
56
+
57
+ all_files = [f for f in all_files if os.path.exists(f)]
58
+
59
+
60
+ band_indices = [b - 1 for b in used_bands]
61
+ num_bands = len(band_indices)
62
+
63
+ count = 0
64
+ mean = np.zeros(num_bands, dtype=np.float64)
65
+ m2 = np.zeros(num_bands, dtype=np.float64)
66
+
67
+ for file_path in tqdm(all_files, desc="Computing statistics"):
68
+ try:
69
+ with rasterio.open(file_path) as src:
70
+
71
+ data = src.read()
72
+
73
+
74
+ if data.shape[0] < max(used_bands):
75
+ print(f"\nWarning: {os.path.basename(file_path)} has only {data.shape[0]} bands, skipping...")
76
+ continue
77
+
78
+ selected_bands = data[band_indices, :, :]
79
+
80
+ num_pixels = selected_bands.shape[1] * selected_bands.shape[2]
81
+ pixels = selected_bands.reshape(num_bands, -1)
82
+
83
+ for i in range(num_pixels):
84
+ pixel_values = pixels[:, i]
85
+
86
+ if np.any(np.isnan(pixel_values)) or np.any(np.isinf(pixel_values)):
87
+ continue
88
+
89
+ count += 1
90
+ delta = pixel_values - mean
91
+ mean += delta / count
92
+ delta2 = pixel_values - mean
93
+ m2 += delta * delta2
94
+
95
+ except Exception as e:
96
+ print(f"\nError processing {os.path.basename(file_path)}: {e}")
97
+ continue
98
+
99
+ if count == 0:
100
+ raise ValueError("No valid pixels found in dataset!")
101
+
102
+ variance = m2 / count
103
+ std = np.sqrt(variance)
104
+
105
+ print("\nFormatted for code:")
106
+ print(f"MEANS = [{', '.join([f'{m:.8f}' for m in mean])}]")
107
+ print(f"STDS = [{', '.join([f'{s:.8f}' for s in std])}]")
108
+
109
+ return mean.tolist(), std.tolist()
110
+
111
+
112
+ if __name__ == "__main__":
113
+
114
+ data_root = "./datasets/Timor_ML4Floods"
115
+
116
+ means, stds = calculate_s2_statistics(data_root)