-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1037 lines (880 loc) · 32.6 KB
/
utils.py
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import glob
import os
import asyncio
import json
import rasterio.coords
import requests
import rasterio
from rasterio.plot import show
from zipfile import ZipFile
import pandas as pd
import shutil
from rasterio.enums import Resampling
import matplotlib.pyplot as plt
from rasterio.warp import calculate_default_transform, reproject
import numpy as np
import imageio
import cv2 as cv
from pyproj import Proj
from rasterio.coords import BoundingBox
from typing import Union
from itertools import product as itrprod
import re
def get_sentinel_filenames(
polygon_list: list[str],
years: list[str],
products: list[str] = ["GRD", "SLC"],
is_poly_bbox: bool = True,
satellite: str = "S1",
instrument: str = "C-SAR",
identifier: str = "",
output_file_path: str = "",
includes: list[str] = [],
return_query_only: bool = False,
):
"""
Get scene names for S1 via direct requet to SARA server
"""
s_names = []
if os.path.isfile(output_file_path):
with open(output_file_path, "r") as f:
for l in f:
s_names.append(l.strip())
else:
start = f"{years[0]}-01-01"
end = f"{years[1]}-12-31"
query = f"https://copernicus.nci.org.au/sara.server/1.0/api/collections/{satellite}/search.json?_pretty=1&startDate={start}&completionDate={end}&instrument={instrument}&maxRecords=500"
if satellite == "S1":
query += "&sensor=IW"
else:
products = []
if identifier != "":
query += f"&identifier={identifier}"
if len(polygon_list) == 0:
polygon_list = [""]
if len(products) == 0:
products = [""]
for poly, prod in list(itrprod(polygon_list, products)):
if poly == "":
poly_query = ""
else:
poly_query = f'&{"box" if is_poly_bbox else "geometry"}={poly}'
if prod == "":
prod_query = ""
else:
prod_query = f"&productType={prod}"
no_page_query = query + poly_query + prod_query
page = 1
query_resp = ["start"]
while query_resp != []:
to_query = no_page_query + f"&page={page}"
if return_query_only:
s_names.append(to_query)
else:
print(f"Querying: {to_query}", end="\r")
response = json.loads(requests.get(to_query).content)
if "features" not in response:
query_resp = []
continue
query_resp = [
r["properties"]["title"] for r in response["features"]
]
s_names.extend(query_resp)
if return_query_only:
break
page += 1
if (return_query_only) and (len(includes) != 0):
print("Filtering the outputs does not work in return query only mode.")
else:
filtered_list = []
for p in includes:
filtered_list.extend(
list(filter(lambda el: len(re.findall(p, el)) != 0, s_names))
)
s_names = list(set(filtered_list))
if output_file_path != "":
with open(output_file_path, "w") as f:
for n in s_names:
f.write(f"{n}\n")
return s_names
def save_file_list(file_list: dict, save_path: str) -> None:
"""
Saves the retrieved data.
"""
with open(save_path, "w") as f:
for k, v in file_list.items():
for filename in v:
f.write(f"{k},{filename}\n")
return None
async def find_all_files_for_case(query_case: tuple, sat_data_dir: str) -> bool:
"""
Finds all files for a selected case of product/year/month
"""
case_path = os.path.join(
sat_data_dir, query_case[0], query_case[1], f"{query_case[1]}-{query_case[2]}"
)
print(f"Retrieving files for {case_path}", end="\r")
return glob.glob(case_path + "/*/*.zip")
async def find_aoi_files(aoi: str, all_files: list[str]) -> list[str]:
"""
Filters all files and finds files for the area of interest.
"""
print(f"filtering files for {aoi}", end="\r")
return list(filter(lambda p: len(re.findall(aoi, p)) != 0, all_files))
def flatten(l: list[list]) -> list:
"""
Flattens the list
"""
return [x for xs in l for x in xs]
# Not sure if async runs well in notebook
async def find_files_for_aios_async(
query_cases: list[tuple],
sat_data_dir: str,
aoi_list: list[str],
) -> dict:
"""
Asyncronously finds the files for an AOI list given as list of identifiers based on a combination of produt/year/month from NCI Copernicus databse.
Set `is_s1` to True for Sentinel-1.
"""
all_files_async = [find_all_files_for_case(c, sat_data_dir) for c in query_cases]
all_files = await asyncio.gather(*all_files_async)
all_files = flatten(all_files)
print("")
aoi_files_async = [find_aoi_files(aoi, all_files) for aoi in aoi_list]
aoi_files = await asyncio.gather(*aoi_files_async)
print("")
return dict(map(lambda k, v: (k, v), aoi_list, aoi_files))
# syncronous function for all cases and AOIs at the same time. Could take long
def find_files_for_aios(
query_cases: list[tuple],
sat_data_dir: str,
aoi_list: list[str],
) -> dict:
"""
Finds the files for an AOI list given as list of identifiers based on a combination of produt/year/month from NCI Copernicus databse.
Set `is_s1` to True for Sentinel-1.
"""
all_files = []
aoi_files = []
for c in query_cases:
case_path = os.path.join(sat_data_dir, c[0], c[1], f"{c[1]}-{c[2]}")
print("\r", f"Retrieving files for {case_path}", end="")
all_files.extend(glob.glob(case_path + "/*/*.zip"))
print("")
aoi_files = {}
for aoi in aoi_list:
print("\r", f"filtering files for {aoi}", end="")
aoi_files[aoi] = list(filter(lambda p: aoi in p, all_files))
print("")
return aoi_files
def find_files_for_s1_aois(nci_files_dict: dict, s1_file_names: list[str]) -> dict:
"""
Finds the files found from SARA server inside the AOI files retrieved from NCI
"""
files_dict = {}
for k, v in nci_files_dict.items():
nci_files = [os.path.splitext(os.path.basename(f))[0] for f in v]
found_idx = [nci_files.index(f) for f in s1_file_names if f in nci_files]
found = [v[idx] for idx in found_idx]
files_dict[k] = found
return files_dict
def find_polarisation_files_s1(dir: str) -> list[str]:
"""
Finds Sentinel 1 data from the provided path.
"""
return glob.glob(os.path.join(dir, "measurement", "*"))
def load_s1_scenes(
zip_file_path: str,
zip_file_id: str,
subdir_name: str = "",
remove_input: bool = True,
) -> tuple:
"""
Loads S1 scenes from provided path and id
* `zip_file_path` and `zip_file_ids` are the path and id of the data.
* `subdir_name` will be added to the output directory path if provided
"""
with ZipFile(zip_file_path) as f:
f.extractall(f"./data/inputs/{zip_file_id}/{subdir_name}")
data_dir = os.listdir(f"./data/inputs/{zip_file_id}/{subdir_name}")[0]
dir = os.path.join(f"./data/inputs/{zip_file_id}/{subdir_name}", data_dir)
band_files = find_polarisation_files_s1(dir)
scenes = [rasterio.open(band_file) for band_file in band_files]
if remove_input:
shutil.rmtree(f"./data/inputs/{zip_file_id}/{subdir_name}", ignore_errors=True)
return scenes
def transform_s1_data(
scenes,
scale_factor=0.03,
) -> tuple:
"""
Downsamples a list of scenes and returns their new data and affine transformations.
"""
new_data = []
new_transforms = []
names = []
for scene in scenes:
new_datum, new_transform = downsample_dataset(scene.name, scale_factor)
new_data.append(new_datum)
new_transforms.append(new_transform)
names.append(os.path.splitext(os.path.basename(scene.name))[0])
return new_data, new_transforms, names
def enhance_color_s1(data, is_slc: bool = True):
"""
Enhances the generated data for better visualisation
"""
if is_slc:
amplitude = np.linalg.norm(data, axis=0)
amplitude = 10 * np.log10(amplitude + 2.0e-10)
else:
amplitude = data / 256
amplitude = amplitude.astype("float64")
amplitude *= 255 / amplitude.max()
return amplitude.astype("uint8")
def plot_scenes_s1(data, data_names, data_transforms, is_slc: bool = True):
"""
Plots the data given the names of the scenes and their affine transformations
"""
_, axes = plt.subplots(1, len(data), figsize=(10 * len(data), 10 * len(data)))
if type(axes) != np.ndarray:
axes = [axes]
for i, d in enumerate(data):
ax = axes[i]
show(
enhance_color_s1(d, is_slc),
ax=ax,
title=f"{data_names[i]}",
transform=data_transforms[i],
)
ax.set_title(f"{data_names[i]}")
ax.title.set_size(10)
def get_scenes_dict(
data_df: pd.DataFrame, product: list[str] = [], is_s1: bool = True
) -> dict:
scenes_dict = {}
id_list = data_df.ID.unique()
for id in id_list:
filtered_df = data_df[data_df.ID == id].reset_index(drop=True)
if product != []:
for p in product:
filtered_df = filtered_df[
filtered_df.Path.apply(lambda x: p in x)
].reset_index(drop=True)
grouper = filtered_df.Path.apply(
lambda r: os.path.split(r)[1].split("_")[5 if is_s1 else 2][0:6]
)
secene_list = [
list(filtered_df.groupby(grouper))[i][1].Path.iloc[0]
for i in range(0, len(grouper.unique()))
]
scenes_dict[id] = secene_list
return scenes_dict
def scale_transform(
warp_matrix: np.ndarray, resolution_ratio_y: float, resolution_ratio_x: float
) -> np.ndarray:
scaled_warp = warp_matrix.copy()
scaled_warp[:, 0] /= resolution_ratio_x
scaled_warp[:, 1] /= resolution_ratio_y
scaled_warp[0, 2] += (1 - resolution_ratio_x) * abs(scaled_warp[0, 0]) / 2
scaled_warp[1, 2] -= (1 - resolution_ratio_y) * abs(scaled_warp[1, 1]) / 2
return scaled_warp
def readjust_origin_for_new_pixel_size(
transform: rasterio.Affine, scale_factor_y: float, scale_factor_x: float
) -> rasterio.Affine:
"""
Readjusts the origin of a scene after resampling.
"""
new_orig_x = transform.c + ((1 - scale_factor_x) * abs(transform.a) / 2)
new_orig_y = transform.f - ((1 - scale_factor_y) * abs(transform.e) / 2)
return rasterio.Affine(
transform.a, transform.b, new_orig_x, transform.d, transform.e, new_orig_y
)
def downsample_dataset(
dataset_path: str,
scale_factor: Union[float, list[float]],
output_file: str = "",
enhance_function=None,
):
"""
Downsamples the output data and returns the new downsampled data and its new affine transformation according to `scale_factor`
"""
with rasterio.open(dataset_path) as dataset:
# resample data to target shape
if type(scale_factor) == float:
scale_factor = [scale_factor] * 2
data = dataset.read(
out_shape=(
dataset.count,
int(dataset.height * scale_factor[0]),
int(dataset.width * scale_factor[1]),
),
resampling=Resampling.bilinear,
)
if enhance_function is not None:
data = enhance_function(data)
# scale image transform
transform = dataset.transform * dataset.transform.scale(
(dataset.width / data.shape[-1]), (dataset.height / data.shape[-2])
)
transform = readjust_origin_for_new_pixel_size(transform, *scale_factor)
profile = dataset.profile
profile.update(
transform=transform,
width=data.shape[2],
height=data.shape[1],
dtype=data.dtype,
)
if output_file != "":
with rasterio.open(output_file, "w", **profile) as ds:
for i in range(0, profile["count"]):
ds.write(data[i], i + 1)
return data, transform
def enhance_color_matching(data, uint16: bool = False):
"""
Increases the brightness of the output data
"""
if uint16:
data = data / 256
data = data.astype("float64")
data *= 255 / data.max()
return data.astype("uint8")
def plot_matching(
datasets, alpha: float = 0.65, plot_title: str = "", save_fig_path: str = ""
):
_, axes = plt.subplots(3, 3, figsize=(10, 10))
show(datasets[0][0], ax=axes[0, 0], title="Reference scene")
show(datasets[0][0], ax=axes[1, 0], title="Reference scene")
show(datasets[0][0], ax=axes[2, 0], title="Reference scene")
show(datasets[1][0], ax=axes[0, 1], title="Target scene")
show(datasets[2][0], ax=axes[1, 1], title="Global matching")
show(datasets[3][0], ax=axes[2, 1], title="Local matching")
show(
((datasets[0][0] * alpha) + (datasets[1][0] * (1 - alpha))).astype("uint8"),
ax=axes[0, 2],
title="Reference + Target ",
)
show(
((datasets[0][0] * alpha) + (datasets[2][0] * (1 - alpha))).astype("uint8"),
ax=axes[1, 2],
title="Reference + Global matching",
)
show(
((datasets[0][0] * alpha) + (datasets[3][0] * (1 - alpha))).astype("uint8"),
ax=axes[2, 2],
title="Reference + Local matching",
)
for ax in axes.ravel():
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
if plot_title != "":
plt.suptitle(plot_title)
if save_fig_path != "":
plt.savefig(save_fig_path)
plt.subplots_adjust(top=0.9)
def reproject_tif(src_path, dst_path, dst_crs):
with rasterio.open(src_path) as src:
print(f"reprojecting from {src.crs} to {dst_crs}")
transform, width, height = calculate_default_transform(
src.crs, dst_crs, src.width, src.height, *src.bounds
)
kwargs = src.meta.copy()
kwargs.update(
{"crs": dst_crs, "transform": transform, "width": width, "height": height}
)
print(f"saving - {dst_path}")
with rasterio.open(dst_path, "w", **kwargs) as dst:
for i in range(1, src.count + 1):
reproject(
source=rasterio.band(src, i),
destination=rasterio.band(dst, i),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform,
dst_crs=dst_crs,
resampling=Resampling.nearest,
)
flip_img = lambda img: np.flipud(np.rot90(img.T))
def adjust_resolutions(
dataset_paths: list[str],
output_paths: list[str],
resampling_resolution: str = "lower",
):
"""
Adjusts the resolutions for two or more datasets with different ones. Rounding errors might cause a slightly different output resolutions.
"""
ps_x = []
ps_y = []
for ds in dataset_paths:
raster = rasterio.open(ds)
raster_px_size = abs(raster.profile["transform"].a)
raster_py_size = abs(raster.profile["transform"].e)
ps_x.append(raster_px_size)
ps_y.append(raster_py_size)
if resampling_resolution == "lower":
ref_res_x = max(ps_x)
ref_res_y = max(ps_y)
else:
ref_res_x = min(ps_x)
ref_res_y = min(ps_y)
scale_factors = []
for sx, sy in zip(ps_x, ps_y):
scale_factors.append(
[
sy / ref_res_y,
sx / ref_res_x,
]
)
transforms = []
for i, ds in enumerate(dataset_paths):
transforms.append(downsample_dataset(ds, scale_factors[i], output_paths[i])[1])
return [[abs(t.a), abs(t.e), t] for t in transforms]
def find_overlap(
dataset_1: str,
dataset_2: str,
return_pixels: bool = False,
return_images: bool = False,
resampling_resolution: str = "lower",
):
"""
Crude overlap finder for two overlapping scenes. (finds the bounding box around the overlapping area.
A better way is to straighten the images and then find the overlap and then revert the transform.)
"""
raster_1 = rasterio.open(dataset_1)
raster_2 = rasterio.open(dataset_2)
bounds_1 = raster_1.bounds
bounds_2 = raster_2.bounds
if return_pixels:
raster_1_px_size = abs(raster_1.profile["transform"].a)
raster_1_py_size = abs(raster_1.profile["transform"].e)
raster_2_px_size = abs(raster_2.profile["transform"].a)
raster_2_py_size = abs(raster_2.profile["transform"].e)
if (raster_1_px_size != raster_2_px_size) or (
raster_1_py_size != raster_2_py_size
):
print(
f"WARNING: Ground resolutions are different for the provided images. Setting it to the {resampling_resolution} resolution."
)
os.makedirs("temp", exist_ok=True)
outputs = adjust_resolutions(
[dataset_1, dataset_2],
["temp/scaled_raster_1.tif", "temp/scaled_raster_2.tif"],
resampling_resolution,
)
dataset_1 = "temp/scaled_raster_1.tif"
dataset_2 = "temp/scaled_raster_2.tif"
(raster_1_px_size, raster_1_py_size, _), (
raster_2_px_size,
raster_2_py_size,
_,
) = outputs
min_left = min(
bounds_1.left // raster_1_px_size, bounds_2.left // raster_2_px_size
)
max_top = max(
bounds_1.top // raster_1_py_size, bounds_2.top // raster_2_py_size
)
bounds_1 = rasterio.coords.BoundingBox(
int(bounds_1.left // raster_1_px_size - min_left),
int(max_top - bounds_1.bottom // raster_1_py_size),
int(bounds_1.right // raster_1_px_size - min_left),
int(max_top - bounds_1.top // raster_1_py_size),
)
bounds_2 = rasterio.coords.BoundingBox(
int(bounds_2.left // raster_2_px_size - min_left),
int(max_top - bounds_2.bottom // raster_2_py_size),
int(bounds_2.right // raster_2_px_size - min_left),
int(max_top - bounds_2.top // raster_2_py_size),
)
overlap_left = max(bounds_1.left, bounds_2.left)
overlap_bottom = (
min(bounds_1.bottom, bounds_2.bottom)
if return_pixels
else max(bounds_1.bottom, bounds_2.bottom)
)
overlap_right = min(bounds_1.right, bounds_2.right)
overlap_top = (
max(bounds_1.top, bounds_2.top)
if return_pixels
else min(bounds_1.top, bounds_2.top)
)
x_condition = (overlap_right - overlap_left) > 0
y_condition = (
(overlap_bottom - overlap_top) > 0
if return_pixels
else (overlap_top - overlap_bottom) > 0
)
assert x_condition and y_condition, "The provided scenes do not overlap"
overlap_in_mosaic = rasterio.coords.BoundingBox(
overlap_left, overlap_bottom, overlap_right, overlap_top
)
mosaic = None
mosaic_overlap = None
raster_overlap_1 = None
raster_overlap_2 = None
if return_images:
mosaic, warps, _ = make_mosaic([dataset_1, dataset_2], return_warps=True)
mosaic_overlap = mosaic[
overlap_in_mosaic.top : overlap_in_mosaic.bottom,
overlap_in_mosaic.left : overlap_in_mosaic.right,
:,
]
raster_overlap_1 = warps[0][
overlap_in_mosaic.top : overlap_in_mosaic.bottom,
overlap_in_mosaic.left : overlap_in_mosaic.right,
:,
]
raster_overlap_2 = warps[1][
overlap_in_mosaic.top : overlap_in_mosaic.bottom,
overlap_in_mosaic.left : overlap_in_mosaic.right,
:,
]
shutil.rmtree("temp", ignore_errors=True)
return overlap_in_mosaic, (
mosaic,
mosaic_overlap,
raster_overlap_1,
raster_overlap_2,
)
def make_mosaic(
dataset_paths: list[str],
offset_x: int = 0,
offset_y: int = 0,
return_warps: bool = False,
resolution_adjustment: bool = False,
resampling_resolution: str = "lower",
):
"""
Creates a mosaic of overlapping scenes. Offsets will be added to the size of the final mosaic if specified.
NOTE: dataset ground resolutions should be the same. Use `resolution_adjustment` flag to fix the unequal resolutions.
"""
if resolution_adjustment:
os.makedirs("temp", exist_ok=True)
new_dataset_paths = [
os.path.join("temp", f"scaled_raster_{i}.tif")
for i in range(len(dataset_paths))
]
adjust_resolutions(
dataset_paths,
new_dataset_paths,
resampling_resolution,
)
dataset_paths = new_dataset_paths
ps_x = []
ps_y = []
rasters = []
transforms = []
for p in dataset_paths:
raster = rasterio.open(p)
transform = raster.profile["transform"]
ps_x.append(abs(round(transform.a)))
ps_y.append(abs(round(transform.e)))
rasters.append(raster)
transforms.append(transform)
ps_x_condition = all(ps == ps_x[0] for ps in ps_x)
ps_y_conditoin = all(ps == ps_y[0] for ps in ps_y)
assert (
ps_x_condition and ps_y_conditoin
), "Ground resolutions are different for datasets. Please use `resolution_adjustment` flag first to fix the issue."
lefts = []
rights = []
tops = []
bottoms = []
for r in rasters:
bounds = r.bounds
lefts.append(abs(bounds.left // transform.a))
rights.append(abs(bounds.right // transform.a))
tops.append(abs(bounds.top // transform.e))
bottoms.append(abs(bounds.bottom // transform.e))
min_left = min(lefts)
min_bottom = min(bottoms)
max_right = max(rights)
max_top = max(tops)
new_shape = (
int(max_top - min_bottom) + offset_y,
int(max_right - min_left) + offset_x,
)
new_transforms = []
for t in transforms:
new_transforms.append(
np.array(
[
[1.0, abs(t.b // t.e), t.c // t.a - min_left],
[t.d // t.a, 1.0, max_top - abs(t.f // t.e)],
]
)
)
mosaic = np.zeros((*new_shape, 3)).astype("uint8")
warps = []
for i, rs in enumerate(rasters):
img = flip_img(rs.read())
imgw = cv.warpAffine(img, new_transforms[i], (new_shape[1], new_shape[0]))
if len(imgw.shape) == 2:
idx = np.where(imgw != 0)
for i in range(0, 3):
mosaic[idx[0], idx[1], i] = imgw[idx[0], idx[1]]
else:
idx = np.where(cv.cvtColor(imgw, cv.COLOR_BGR2GRAY) != 0)
mosaic[idx[0], idx[1], :] = imgw[idx[0], idx[1], :]
if return_warps:
warp = np.zeros_like(imgw).astype("uint8")
if len(imgw.shape) == 2:
warp[idx[0], idx[1]] = imgw[idx[0], idx[1]]
else:
warp[idx[0], idx[1], :] = imgw[idx[0], idx[1], :]
warps.append(warp)
if resolution_adjustment:
shutil.rmtree("temp", ignore_errors=True)
return mosaic, warps, new_transforms
def simple_mosaic(img_list):
"""
A simple mosaic of two image by overlapping the non-zero parts in a consecutive order.
Assumes all images are the same size and ignores any transformations.
"""
mosaic = np.zeros_like(img_list[0]).astype("uint8")
for img in img_list:
if len(img.shape) == 2:
idx = np.where(img != 0)
mosaic[idx[0], idx[1]] = img[idx[0], idx[1]]
else:
idx = np.where(cv.cvtColor(img, cv.COLOR_BGR2GRAY) != 0)
mosaic[idx[0], idx[1], :] = img[idx[0], idx[1], :]
return mosaic
def make_difference_gif(
images_list: list[str],
output_path: str,
titles_list: list[str] = [],
scale_factor: float = -1.0,
mosaic_scenes: bool = False,
mosaic_offsets_x: list[int] = [],
mosaic_offsets_y: list[int] = [],
):
os.makedirs("temp", exist_ok=True)
temp_paths = [os.path.join("temp", os.path.basename(f)) for f in images_list]
if scale_factor != -1.0:
for i, p in enumerate(temp_paths):
downsample_dataset(images_list[i], scale_factor, p)
else:
temp_paths = images_list
if len(titles_list) > 0:
assert (
len(titles_list) == len(images_list)
if not mosaic_scenes
else len(images_list) - 1
), "Length of provided list of titles does not match the number of images."
else:
titles_list = [os.path.splitext(os.path.basename(f))[0] for f in images_list]
images = []
font = cv.FONT_HERSHEY_SIMPLEX
# origin
origin = (5, 50)
font_scale = 1.5
# Blue color in BGR
color = (255, 0, 0)
# Line thickness
thickness = 3
if mosaic_scenes:
ref_scene = temp_paths[0]
tgt_scenes = temp_paths[1:]
if len(mosaic_offsets_x) == 0:
mosaic_offsets_x = [0] * len(tgt_scenes)
if len(mosaic_offsets_y) == 0:
mosaic_offsets_y = [0] * len(tgt_scenes)
for i, p in enumerate(tgt_scenes):
img, _, _ = make_mosaic(
[ref_scene, p], mosaic_offsets_x[i], mosaic_offsets_y[i]
)
cv.putText(
img,
titles_list[i],
origin,
font,
font_scale,
color,
thickness,
cv.LINE_AA,
)
images.append(img)
else:
for i, p in enumerate(temp_paths):
img = rasterio.open(p).read()
img = flip_img(img).copy()
cv.putText(
img,
titles_list[i],
origin,
font,
font_scale,
color,
thickness,
cv.LINE_AA,
)
images.append(img)
imageio.mimwrite(output_path, images, loop=0, fps=1)
shutil.rmtree("temp", ignore_errors=True)
def find_band_files_s2(dir: str, selected_res_index: int = -1) -> list[str]:
"""
Retrieving band files from the data path `dir`, If there are multiple resolutions of the data, `selected_res_index` must be specified as a positive integer.
"""
if selected_res_index == -1:
band_files = [
file
for file in glob.glob(os.path.join(dir, "GRANULE", "*", "IMG_DATA", "*"))
]
else:
band_dirs = [
file
for file in glob.glob(os.path.join(dir, "GRANULE", "*", "IMG_DATA", "*"))
]
selected_res = band_dirs[selected_res_index]
band_files = glob.glob(f"{selected_res}/*")
return band_files
def load_s2_bands(
zip_file_path: str,
zip_file_id: str,
s2_other_bands_list: list[str],
subdir_name: str = "",
remove_input: bool = True,
selected_res_index: int = -1,
) -> tuple:
"""
Loads bands from the data.
* `zip_file_path` and `zip_file_ids` are the path and id of the data.
* The function also loads the other bands specified in the other bands list
* `subdir_name` will be added to the output directory path if provided
* If there are multiple resolutions of the data, `selected_res_index` must be specified as a positive integer
"""
with ZipFile(zip_file_path) as f:
f.extractall(f"./data/inputs/{zip_file_id}/{subdir_name}")
data_dir = os.listdir(f"./data/inputs/{zip_file_id}/{subdir_name}")[0]
dir = os.path.join(f"./data/inputs/{zip_file_id}/{subdir_name}", data_dir)
band_files = find_band_files_s2(dir, selected_res_index)
other_band_files = []
for suffix in s2_other_bands_list:
other_band = list(filter(lambda b: suffix in b, band_files))
if other_band != []:
other_band_files.append(other_band[0])
band_files = [bf for bf in band_files if bf not in other_band_files]
bands = [rasterio.open(band_file) for band_file in band_files]
other_bands = []
for bf in other_band_files:
other_bands.append(rasterio.open(bf))
if remove_input:
shutil.rmtree(f"./data/inputs/{zip_file_id}/{subdir_name}", ignore_errors=True)
return bands, other_band
def write_true_color_s2(
zip_id: str,
true_bands,
band_profile,
scale_factor=0.03,
subdir_name="",
) -> tuple:
"""
writes a true color image using true color bands (not TCI). The updated profile for true bands shold be provided.
also downsamples the output data and returns the new downsampled data and its new affine transformation according to `scale_factor`
"""
output_dir = f"./data/outputs/{zip_id}/{subdir_name}/"
if os.path.isdir(output_dir):
shutil.rmtree(output_dir, ignore_errors=True)
os.makedirs(output_dir, exist_ok=True)
with rasterio.open(f"{output_dir}/out.tif", "w", **band_profile) as dest_file:
for i, b in enumerate(true_bands):
dest_file.write(b.read(1), i + 1)
new_data, new_transform = downsample_dataset(f"{output_dir}/out.tif", scale_factor)
return new_data, new_transform
def enhance_color_s2(data, uint16: bool = False):
"""
Increases the brightness of the output data
"""
if uint16:
data = data / 256
data = data.astype("float64")
data *= 255 / data.max()
return data.astype("uint8")
def extract_true_bands(bands):
"Extracts true color bands and retuns them together with an updated profile for the bands"
true_bands = [
b
for b in bands
if os.path.basename(b.name).split("_")[2].replace(".jp2", "").strip()
in ["B02", "B03", "B04"]
]
sortperm = np.argsort([b.name for b in true_bands])
true_bands = [true_bands[i] for i in sortperm]
band_profile = true_bands[0].profile
band_profile.update({"count": len(true_bands)})
return true_bands, band_profile
def plot_scene_s2(data, data_transform):
"""
Plots the true color image and blue band of the scene given the names of the scenes and their affine transformation
"""
_, (axt, axb) = plt.subplots(1, 2, figsize=(10, 20))
show(
enhance_color_s2(data[1]),
ax=axb,
title="Single color band (B)",
cmap="Blues",
transform=data_transform,
)
show(
enhance_color_s2(data),
ax=axt,
title="True colour bands image",
transform=data_transform,
)
def resize_bbox(bbox, scale_factor=1.0):
x_dim = bbox.right - bbox.left
y_dim = bbox.top - bbox.bottom
dx = ((scale_factor - 1) * x_dim) / 2
dy = ((scale_factor - 1) * y_dim) / 2
return BoundingBox(bbox.left - dx, bbox.bottom - dy, bbox.right + dx, bbox.top + dy)
def find_scene_bounding_box_lla(scene: str, scale_factor=1.0):
raster = rasterio.open(scene)
raster_bounds = raster.bounds
raster_bounds = resize_bbox(raster_bounds, scale_factor)
raster_crs = raster.crs
raster_proj = Proj(**raster_crs.data)
west, south = raster_proj(raster_bounds.left, raster_bounds.bottom, inverse=True)
east, north = raster_proj(raster_bounds.right, raster_bounds.top, inverse=True)
bbox = f"{west},{south},{east},{north}"
return bbox
def warp_affine_dataset(
dataset: Union[str, np.ndarray],
output_path: str = "",
translation_x: float = 0.0,
translation_y: float = 0.0,
rotation_angle: float = 0.0,
scale: float = 1.0,
):