-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathgetImagesLib.py
More file actions
10598 lines (9422 loc) · 352 KB
/
getImagesLib.py
File metadata and controls
10598 lines (9422 loc) · 352 KB
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
"""
Get images and organize them so they are easier to work with
geeViz.getImagesLib is the core module for setting up various imageCollections from GEE. Notably, it facilitates Landsat, Sentinel-2, and MODIS data organization. This module helps avoid many common mistakes in GEE. Most functions ease matching band names, ensuring resampling methods are properly set, date wrapping, and helping with cloud and cloud shadow masking.
"""
"""
Copyright 2026 Ian Housman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# %%
# Script to help with data prep, analysis, and delivery from GEE
# Intended to work within the geeViz package
######################################################################
from geeViz.geeView import *
import geeViz.cloudStorageManagerLib as cml
import geeViz.assetManagerLib as aml
import geeViz.taskManagerLib as tml
import math, ee, json, pdb, datetime
from threading import Thread
# %%
######################################################################
# Module for getting Landsat, Sentinel 2 and MODIS images/composites
# Define visualization parameters
vizParamsFalse = {
"min": 0.05,
"max": [0.5, 0.6, 0.6],
"bands": "swir1,nir,red",
"gamma": 1.6,
}
vizParamsFalse10k = {
"min": 0.05 * 10000,
"max": [0.5 * 10000, 0.6 * 10000, 0.6 * 10000],
"bands": "swir1,nir,red",
"gamma": 1.6,
}
vizParamsTrue = {"min": 0, "max": [0.2, 0.2, 0.2], "bands": "red,green,blue"}
vizParamsTrue10k = {
"min": 0,
"max": [0.2 * 10000, 0.2 * 10000, 0.2 * 10000],
"bands": "red,green,blue",
}
common_projections = {}
common_projections["NLCD_CONUS"] = {
"crs": 'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["latitude_of_center",23],PARAMETER["longitude_of_center",-96],PARAMETER["standard_parallel_1",29.5],PARAMETER["standard_parallel_2",45.5],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1],AXIS["Easting",EAST],AXIS["Northing",NORTH]]',
"transform": [30, 0, -2361915.0, 0, -30, 3177735.0],
}
common_projections["NLCD_AK"] = {
"crs": 'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9108"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",55],PARAMETER["standard_parallel_2",65],PARAMETER["latitude_of_center",50],PARAMETER["longitude_of_center",-154],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1]]',
"transform": [30, 0, -48915.0, 0, -30, 1319415.0],
}
common_projections["NLCD_HI"] = {
"crs": 'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984", SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich", 0.0], UNIT["degree", 0.017453292519943295], AXIS["Longitude", EAST], AXIS["Latitude", NORTH], AUTHORITY["EPSG","4326"]], PROJECTION["Albers_Conic_Equal_Area"], PARAMETER["central_meridian", -157.0],PARAMETER["latitude_of_origin", 3.0],PARAMETER["standard_parallel_1", 8.0],PARAMETER["false_easting", 0.0],PARAMETER["false_northing", 0.0],PARAMETER["standard_parallel_2", 18.0],UNIT["m", 1.0],AXIS["x", EAST],AXIS["y", NORTH]]',
"transform": [30, 0, -342585, 0, -30, 2127135],
}
######################################################################
# UTM zone and EPSG code utilities
######################################################################
def getUTMZone(longitude: float) -> int:
"""Return the UTM zone number (1-60) for a given longitude.
Args:
longitude: Longitude in decimal degrees (-180 to 180).
Returns:
UTM zone number (1-60).
Examples:
>>> getUTMZone(-113.15)
12
>>> getUTMZone(2.35)
31
"""
longitude = ((longitude + 180) % 360) - 180 # normalize to [-180, 180)
zone = int((longitude + 180) / 6) + 1
return min(zone, 60)
# Mapping of datum name -> (north EPSG prefix, south EPSG prefix)
# The full code is prefix * 100 + zone (e.g. WGS84 North zone 12 = 32600 + 12 = 32612)
_UTM_DATUM_EPSG = {
"WGS84": (326, 327),
"NAD83": (269, 321), # NAD83 North: EPSG:269xx, South: EPSG:321xx
"NAD27": (267, 267), # NAD27: EPSG:267xx (North America only, N hemisphere)
"WGS72": (322, 323),
"ETRS89": (258, 258), # ETRS89: EPSG:258xx (Europe only, N hemisphere)
"GDA94": (283, 283), # GDA94: EPSG:283xx (Australia, S hemisphere)
"GDA2020": (78, 78), # GDA2020: EPSG:78xx (Australia, zones 46-56)
"SIRGAS2000": (311, 317), # SIRGAS2000 North: 311xx, South: 317xx
}
def getUTMEpsg(location, datum: str = "WGS84") -> str:
"""Return the EPSG code string for a UTM zone given a location and datum.
Combines :func:`getUTMZone` with a datum lookup to produce the full
EPSG code (e.g. ``"EPSG:32612"`` for WGS84 UTM Zone 12N).
Args:
location: One of:
- ``[longitude, latitude]`` list/tuple (GEE convention: lon first).
- ``ee.Geometry.Point`` — coordinates are extracted via ``.getInfo()``.
datum: Datum name. One of ``"WGS84"`` (default), ``"NAD83"``, ``"NAD27"``,
``"WGS72"``, ``"ETRS89"``, ``"GDA94"``, ``"GDA2020"``, ``"SIRGAS2000"``.
Case-insensitive.
Returns:
EPSG code string, e.g. ``"EPSG:32612"``.
Raises:
ValueError: If the datum is not recognized or ``location`` is not a
supported type.
Examples:
>>> getUTMEpsg([-113.15, 47.15])
'EPSG:32612'
>>> getUTMEpsg([-113.15, 47.15], datum="NAD83")
'EPSG:26912'
>>> getUTMEpsg([151.21, -33.86])
'EPSG:32756'
>>> getUTMEpsg(ee.Geometry.Point([-113.15, 47.15]))
'EPSG:32612'
"""
# Parse location into (longitude, latitude)
if isinstance(location, ee.Geometry):
coords = location.coordinates().getInfo()
longitude, latitude = coords[0], coords[1]
elif isinstance(location, (list, tuple)) and len(location) >= 2:
longitude, latitude = location[0], location[1]
else:
raise ValueError(
f"location must be a [lon, lat] list/tuple or ee.Geometry.Point, "
f"got {type(location).__name__}"
)
datum_upper = datum.upper().replace(" ", "").replace("-", "")
if datum_upper not in _UTM_DATUM_EPSG:
raise ValueError(
f"Unknown datum '{datum}'. Supported: {', '.join(sorted(_UTM_DATUM_EPSG.keys()))}"
)
north_prefix, south_prefix = _UTM_DATUM_EPSG[datum_upper]
zone = getUTMZone(longitude)
prefix = north_prefix if latitude >= 0 else south_prefix
return f"EPSG:{prefix}{zone:02d}"
# Direction of a decrease in photosynthetic vegetation- add any that are missing
changeDirDict = {
"blue": 1,
"green": 1,
"red": 1,
"nir": -1,
"swir1": 1,
"swir2": 1,
"temp": 1,
"NDVI": -1,
"NBR": -1,
"NDMI": -1,
"NDSI": 1,
"brightness": 1,
"greenness": -1,
"wetness": -1,
"fourth": -1,
"fifth": 1,
"sixth": -1,
"ND_blue_green": -1,
"ND_blue_red": -1,
"ND_blue_nir": 1,
"ND_blue_swir1": -1,
"ND_blue_swir2": -1,
"ND_green_red": -1,
"ND_green_nir": 1,
"ND_green_swir1": -1,
"ND_green_swir2": -1,
"ND_red_swir1": -1,
"ND_red_swir2": -1,
"ND_nir_red": -1,
"ND_nir_swir1": -1,
"ND_nir_swir2": -1,
"ND_swir1_swir2": -1,
"R_swir1_nir": 1,
"R_red_swir1": -1,
"EVI": -1,
"SAVI": -1,
"IBI": 1,
"tcAngleBG": -1,
"tcAngleGW": -1,
"tcAngleBW": -1,
"tcDistBG": 1,
"tcDistGW": 1,
"tcDistBW": 1,
"NIRv": -1,
"NDCI": -1,
"NDGI": -1,
}
# Precomputed cloudscore offsets and TDOM stats
# These have been pre-computed for all CONUS for Landsat and Setinel 2 (separately)
# and are appropriate to use for any time period within the growing season
# The cloudScore offset is generally some lower percentile of cloudScores on a pixel-wise basis
# The TDOM stats are the mean and standard deviations of the two bands used in TDOM
# By default, TDOM uses the nir and swir1 bands
preComputedCloudScoreOffset = ee.ImageCollection("projects/lcms-tcc-shared/assets/CS-TDOM-Stats/cloudScore").mosaic()
preComputedTDOMStats = ee.ImageCollection("projects/lcms-tcc-shared/assets/CS-TDOM-Stats/TDOM").filter(ee.Filter.eq("endYear", 2019)).mosaic().divide(10000)
def getPrecomputedCloudScoreOffsets(cloudScorePctl=10):
"""Retrieves precomputed cloud score offset images for Landsat and Sentinel-2.
These offsets represent a lower percentile of cloud scores on a pixel-wise basis,
precomputed for all CONUS. They are appropriate for any time period within the
growing season.
Args:
cloudScorePctl (int, optional): The cloud score percentile to use. Defaults to ``10``.
Returns:
dict: A dictionary with keys ``"landsat"`` and ``"sentinel2"``, each containing
an ``ee.Image`` of the cloud score offset for that sensor.
Examples:
>>> offsets = getPrecomputedCloudScoreOffsets(10)
>>> landsat_offset = offsets["landsat"]
>>> sentinel2_offset = offsets["sentinel2"]
"""
return {
"landsat": preComputedCloudScoreOffset.select(["Landsat_CloudScore_p{}".format(cloudScorePctl)]),
"sentinel2": preComputedCloudScoreOffset.select(["Sentinel2_CloudScore_p{}".format(cloudScorePctl)]),
}
def getPrecomputedTDOMStats():
"""Retrieves precomputed TDOM (Temporal Dark Outlier Mask) statistics for Landsat and Sentinel-2.
Returns the mean and standard deviation of the NIR and SWIR1 bands, precomputed
for all CONUS. These are used by the TDOM cloud shadow masking algorithm.
Returns:
dict: A nested dictionary with keys ``"landsat"`` and ``"sentinel2"``, each
containing ``"mean"`` and ``"stdDev"`` keys mapped to ``ee.Image`` objects
with the corresponding band statistics.
Examples:
>>> stats = getPrecomputedTDOMStats()
>>> landsat_mean = stats["landsat"]["mean"]
>>> sentinel2_stddev = stats["sentinel2"]["stdDev"]
"""
return {
"landsat": {
"mean": preComputedTDOMStats.select(["Landsat_nir_mean", "Landsat_swir1_mean"]),
"stdDev": preComputedTDOMStats.select(["Landsat_nir_stdDev", "Landsat_swir1_stdDev"]),
},
"sentinel2": {
"mean": preComputedTDOMStats.select(["Sentinel2_nir_mean", "Sentinel2_swir1_mean"]),
"stdDev": preComputedTDOMStats.select(["Sentinel2_nir_stdDev", "Sentinel2_swir1_stdDev"]),
},
}
######################################################################
# FUNCTIONS
######################################################################
######################################################################
# Function to asynchronously print ee objects
def printEE(eeObject, message=""):
"""Asynchronously prints an Earth Engine object by fetching its value in a background thread.
Args:
eeObject (ee.ComputedObject): Any Earth Engine object to print (e.g., ``ee.Image``,
``ee.Number``, ``ee.Dictionary``).
message (str, optional): A message to print before the object value. Defaults to ``""``.
Returns:
None
Examples:
>>> img = ee.Image("USGS/SRTMGL1_003")
>>> printEE(img.bandNames(), "Band names:")
"""
def printIt(eeObject):
print(message, eeObject.getInfo())
print()
t = Thread(target=printIt, args=(eeObject,))
t.start()
######################################################################
######################################################################
# Function to set null value for export or conversion to arrays
def setNoData(image: ee.Image, noDataValue: float) -> ee.Image:
"""Sets null values for an image, replacing masked pixels with a constant.
Useful for preparing images for export or conversion to arrays where null
values are not supported.
Args:
image (ee.Image): The input Earth Engine image.
noDataValue (float): The value to assign to null (masked) pixels.
Returns:
ee.Image: The image with null pixels replaced by ``noDataValue``.
Examples:
>>> img = ee.Image("USGS/SRTMGL1_003")
>>> filled = setNoData(img, -9999)
"""
image = image.unmask(noDataValue, False) # .set('noDataValue', noDataValue)
return image # .set(args)
######################################################################
######################################################################
# Formats arguments as strings so can be easily set as properties
def formatArgs(args: dict) -> dict:
"""Formats arguments as strings for setting as Earth Engine image properties.
Converts booleans, lists, dicts, and None values to their string representations.
Strings and ints are kept as-is. Other types are omitted.
Args:
args (dict): A dictionary of arguments to format.
Returns:
dict: A dictionary with values converted to strings or kept as str/int.
Examples:
>>> formatted = formatArgs({"threshold": 0.5, "apply": True, "bands": ["nir", "swir1"]})
>>> print(formatted)
{'apply': 'True', 'bands': "['nir', 'swir1']"}
"""
formattedArgs = {}
for key in args.keys():
if type(args[key]) in [bool, list, dict, type(None)]:
formattedArgs[key] = str(args[key])
elif type(args[key]) in [str, int]:
formattedArgs[key] = args[key]
return formattedArgs
######################################################################
######################################################################
# Functions to perform basic clump and elim
def sieve(image: ee.Image, mmu: float) -> ee.Image:
"""Performs clumping and elimination (sieving) on a classified image.
Removes patches smaller than the minimum mapping unit by replacing them
with the focal mode of surrounding pixels.
Args:
image (ee.Image): The input classified Earth Engine image.
mmu (float): The minimum mapping unit in pixels. Patches smaller than
this will be replaced by the focal mode.
Returns:
ee.Image: The sieved image with small patches eliminated.
Examples:
>>> classified = ee.Image("USGS/NLCD/NLCD2019").select("landcover")
>>> sieved = sieve(classified, 5)
"""
args = formatArgs(locals())
connected = image.connectedPixelCount(mmu + 20)
# Map.addLayer(connected,{'min':1,'max':mmu},'connected')
elim = connected.gt(mmu)
mode = image.focal_mode(mmu / 2, "circle")
mode = mode.mask(image.mask())
filled = image.where(elim.Not(), mode)
return filled.set("mmu", mmu).set(args)
# Written by Yang Z.
# ------ L8 to L7 HARMONIZATION FUNCTION -----
# slope and intercept citation: Roy, D.P., Kovalskyy, V., Zhang, H.K., Vermote, E.F., Yan, L., Kumar, S.S, Egorov, A., 2016, Characterization of Landsat-7 to Landsat-8 reflective wavelength and normalized difference vegetation index continuity, Remote Sensing of Environment, 185, 57-70.(http://dx.doi.org/10.1016/j.rse.2015.12.024); Table 2 - reduced major axis (RMA) regression coefficients
def harmonizationRoy(oli: ee.Image) -> ee.Image:
"""Harmonizes Landsat 8 OLI to Landsat 7 ETM+ using Roy et al. (2016) coefficients.
Applies reduced major axis (RMA) regression coefficients from Roy, D.P. et al.
(2016) to transform OLI reflectance to ETM+ equivalent. Operates on the
blue, green, red, nir, swir1, and swir2 bands.
Args:
oli (ee.Image): A Landsat 8 OLI image with bands named ``"blue"``, ``"green"``,
``"red"``, ``"nir"``, ``"swir1"``, ``"swir2"``.
Returns:
ee.Image: The image with spectral bands adjusted to ETM+ equivalents.
Examples:
>>> oli_image = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> harmonized = harmonizationRoy(oli_image)
"""
slopes = ee.Image.constant([0.9785, 0.9542, 0.9825, 1.0073, 1.0171, 0.9949]) # create an image of slopes per band for L8 TO L7 regression line - David Roy
itcp = ee.Image.constant([-0.0095, -0.0016, -0.0022, -0.0021, -0.0030, 0.0029]) # create an image of y-intercepts per band for L8 TO L7 regression line - David Roy
bns = oli.bandNames()
includeBns = ["blue", "green", "red", "nir", "swir1", "swir2"]
otherBns = bns.removeAll(includeBns)
# create an image of y-intercepts per band for L8 TO L7 regression line - David Roy
y = oli.select(includeBns).float().subtract(itcp).divide(slopes).set("system:time_start", oli.get("system:time_start"))
y = y.addBands(oli.select(otherBns)).select(bns)
return y.float()
####################################################################
# Code to implement OLI/ETM/MSI regression
# Chastain et al 2018 coefficients
# Empirical cross sensor comparison of Sentinel-2A and 2B MSI, Landsat-8 OLI, and Landsat-7 ETM+ top of atmosphere spectral characteristics over the conterminous United States
# https://www.sciencedirect.com/science/article/pii/S0034425718305212#t0020
# Left out 8a coefficients since all sensors need to be cross- corrected with bands common to all sensors
# Dependent and Independent variables can be switched since Major Axis (Model 2) linear regression was used
chastainBandNames = ["blue", "green", "red", "nir", "swir1", "swir2"]
# From Table 4
# msi = oli*slope+intercept
# oli = (msi-intercept)/slope
msiOLISlopes = [1.0946, 1.0043, 1.0524, 0.8954, 1.0049, 1.0002]
msiOLIIntercepts = [-0.0107, 0.0026, -0.0015, 0.0033, 0.0065, 0.0046]
# From Table 5
# msi = etm*slope+intercept
# etm = (msi-intercept)/slope
msiETMSlopes = [1.10601, 0.99091, 1.05681, 1.0045, 1.03611, 1.04011]
msiETMIntercepts = [-0.0139, 0.00411, -0.0024, -0.0076, 0.00411, 0.00861]
# From Table 6
# oli = etm*slope+intercept
# etm = (oli-intercept)/slope
oliETMSlopes = [1.03501, 1.00921, 1.01991, 1.14061, 1.04351, 1.05271]
oliETMIntercepts = [-0.0055, -0.0008, -0.0021, -0.0163, -0.0045, 0.00261]
# Construct dictionary to handle all pairwise combos
chastainCoeffDict = {
"MSI_OLI": [msiOLISlopes, msiOLIIntercepts, 1],
"MSI_ETM": [msiETMSlopes, msiETMIntercepts, 1],
"OLI_ETM": [oliETMSlopes, oliETMIntercepts, 1],
"OLI_MSI": [msiOLISlopes, msiOLIIntercepts, 0],
"ETM_MSI": [msiETMSlopes, msiETMIntercepts, 0],
"ETM_OLI": [oliETMSlopes, oliETMIntercepts, 0],
}
# Function to apply model in one direction
def dir0Regression(img, slopes, intercepts):
"""Applies a forward linear regression model: ``corrected = img * slopes + intercepts``.
Used internally by :func:`harmonizationChastain` to apply Chastain et al. (2018)
cross-sensor harmonization in the forward direction.
Args:
img (ee.Image): The input image with spectral bands to correct.
slopes (list[float]): Regression slope coefficients for each band in
``chastainBandNames``.
intercepts (list[float]): Regression intercept coefficients for each band in
``chastainBandNames``.
Returns:
ee.Image: The image with corrected spectral bands and all other bands preserved.
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> corrected = dir0Regression(img, msiOLISlopes, msiOLIIntercepts)
"""
bns = img.bandNames()
nonCorrectBands = bns.removeAll(chastainBandNames)
nonCorrectedBands = img.select(nonCorrectBands)
corrected = img.select(chastainBandNames).multiply(slopes).add(intercepts)
out = corrected.addBands(nonCorrectedBands).select(bns)
return out
# Applying the model in the opposite direction
def dir1Regression(img, slopes, intercepts):
"""Applies an inverse linear regression model: ``corrected = (img - intercepts) / slopes``.
Used internally by :func:`harmonizationChastain` to apply Chastain et al. (2018)
cross-sensor harmonization in the reverse direction.
Args:
img (ee.Image): The input image with spectral bands to correct.
slopes (list[float]): Regression slope coefficients for each band in
``chastainBandNames``.
intercepts (list[float]): Regression intercept coefficients for each band in
``chastainBandNames``.
Returns:
ee.Image: The image with corrected spectral bands and all other bands preserved.
Examples:
>>> img = ee.Image("LANDSAT/LE07/C02/T1_L2/LE07_044034_20200101")
>>> corrected = dir1Regression(img, oliETMSlopes, oliETMIntercepts)
"""
bns = img.bandNames()
nonCorrectBands = bns.removeAll(chastainBandNames)
nonCorrectedBands = img.select(nonCorrectBands)
corrected = img.select(chastainBandNames).subtract(intercepts).divide(slopes)
out = corrected.addBands(nonCorrectedBands).select(bns)
return out
# Function to correct one sensor to another
def harmonizationChastain(img: ee.Image, fromSensor: str, toSensor: str) -> ee.Image:
"""Harmonizes cross-sensor reflectance using Chastain et al. (2018) coefficients.
Supports pairwise harmonization between MSI (Sentinel-2), OLI (Landsat 8/9),
and ETM (Landsat 7) using Model 2 (Major Axis) linear regression coefficients
from Chastain et al. (2018).
Args:
img (ee.Image): The input image with bands named ``"blue"``, ``"green"``,
``"red"``, ``"nir"``, ``"swir1"``, ``"swir2"``.
fromSensor (str): Source sensor identifier. One of ``"MSI"``, ``"OLI"``, or ``"ETM"``.
toSensor (str): Target sensor identifier. One of ``"MSI"``, ``"OLI"``, or ``"ETM"``.
Returns:
ee.Image: The harmonized image with properties ``"fromSensor"`` and ``"toSensor"`` set.
Examples:
>>> oli_img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> harmonized = harmonizationChastain(oli_img, "OLI", "ETM")
"""
args = formatArgs(locals())
# Get the model for the given from and to sensor
comboKey = fromSensor.upper() + "_" + toSensor.upper()
coeffList = chastainCoeffDict[comboKey]
slopes = coeffList[0]
intercepts = coeffList[1]
direction = ee.Number(coeffList[2])
# Apply the model in the respective direction
out = ee.Algorithms.If(
direction.eq(0),
dir0Regression(img, slopes, intercepts),
dir1Regression(img, slopes, intercepts),
)
out = ee.Image(out).copyProperties(img).copyProperties(img, ["system:time_start"])
out = out.set({"fromSensor": fromSensor, "toSensor": toSensor}).set(args)
return ee.Image(out)
####################################################################
# Function to create a multiband image from a collection
def collectionToImage(collection: ee.ImageCollection) -> ee.Image:
"""Converts an image collection to a single multiband image.
.. deprecated::
Use ``ee.ImageCollection.toBands()`` instead, which is more efficient.
Iterates over the collection and stacks all bands into a single image.
Args:
collection (ee.ImageCollection): The input Earth Engine image collection.
Returns:
ee.Image: A multiband image containing all bands from all images in the collection.
Examples:
>>> col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2").limit(3)
>>> stacked = collectionToImage(col)
"""
def cIterator(img, prev):
return ee.Image(prev).addBands(img)
stack = ee.Image(collection.iterate(cIterator, ee.Image(1)))
stack = stack.select(ee.List.sequence(1, stack.bandNames().size().subtract(1)))
return stack
####################################################################
####################################################################
# Function to find the date for a given composite computed from a given set of images
# Will work on composites computed with methods that include different dates across different bands
# such as the median. For something like a medoid, only a single bands needs passed through
# A known bug is that if the same value occurs twice, it will choose only a single date
def compositeDates(images: ee.ImageCollection, composite: ee.Image, bandNames: list = None) -> ee.Image:
"""Finds the acquisition dates corresponding to each band in a composite image.
Works on composites computed with methods that may include different dates across
different bands (e.g., median). For medoid composites, only a single band needs
to be passed through. A known limitation is that if the same pixel value occurs
on two different dates, only one date will be selected.
Args:
images (ee.ImageCollection): The original image collection used to create
the composite.
composite (ee.Image): The composite image whose per-band dates are to be found.
bandNames (list[str] or ee.List, optional): Band names to consider. If ``None``,
uses all bands from the first image in the collection. Defaults to ``None``.
Returns:
ee.Image: A multiband image where each band contains the date (as YYYYDD float)
of the source image that contributed to that band of the composite.
Examples:
>>> col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2").filterDate("2020-06-01", "2020-09-01")
>>> composite = col.median()
>>> dates = compositeDates(col, composite, ["SR_B4", "SR_B5"])
"""
if bandNames == None:
bandNames = ee.Image(images.first()).bandNames()
else:
images = images.select(bandNames)
composite = composite.select(bandNames)
def bnCat(bn):
return ee.String(bn).cat("_diff")
bns = ee.Image(images.first()).bandNames().map(bnCat)
# Function to get the abs diff from a given composite *-1
def getDiff(img):
out = img.subtract(composite).abs().multiply(-1).rename(bns)
return img.addBands(out)
# Find the diff and add a date band
images = images.map(getDiff)
images = images.map(addDateBand)
# Iterate across each band and find the corresponding date to the composite
def bnCat2(bn):
bn = ee.String(bn)
t = images.select([bn, bn.cat("_diff"), "year"]).qualityMosaic(bn.cat("_diff"))
return t.select(["year"]).rename(["YYYYDD"])
out = bandNames.map(bnCat2)
# Convert to an image and rename
out = collectionToImage(ee.ImageCollection(out))
# var outBns = bandNames.map(function(bn){return ee.String(bn).cat('YYYYDD')});
# out = out.rename(outBns);
return out
############################################################################
# Function to handle empty collections that will cause subsequent processes to fail
# If the collection is empty, will fill it with an empty image
def fillEmptyCollections(inCollection: ee.ImageCollection, dummyImage: ee.Image) -> ee.ImageCollection:
"""Fills empty image collections with a fully-masked dummy image.
Prevents downstream errors from empty collections by substituting a single
fully-masked dummy image when the input collection contains no images.
Args:
inCollection (ee.ImageCollection): The input image collection that may be empty.
dummyImage (ee.Image): A template image whose band structure matches the expected
output. It will be fully masked (all pixels set to 0) if used.
Returns:
ee.ImageCollection: The original collection if non-empty, otherwise a collection
containing the fully-masked ``dummyImage``.
Examples:
>>> col = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2").filterDate("2000-01-01", "2000-01-02")
>>> dummy = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> safe_col = fillEmptyCollections(col, dummy)
"""
dummyCollection = ee.ImageCollection([dummyImage.mask(ee.Image(0))])
imageCount = inCollection.toList(1).length()
return ee.ImageCollection(ee.Algorithms.If(imageCount.gt(0), inCollection, dummyCollection))
############################################################################
# Add band tracking which satellite the pixel came from
def addSensorBand(img: ee.Image, whichProgram: str, toaOrSR: str) -> ee.Image:
"""Adds a band encoding the satellite sensor as a numeric value.
Maps satellite names (e.g., ``LANDSAT_8``, ``Sentinel-2A``) to integer codes
(e.g., 8, 21) and adds the result as a ``"sensor"`` band. Also sets the
``"sensor"`` property on the image.
Args:
img (ee.Image): The input Earth Engine image with appropriate spacecraft metadata.
whichProgram (str): The satellite program. One of ``"C1_landsat"``,
``"C2_landsat"``, or ``"sentinel2"``.
toaOrSR (str): The processing level, ``"TOA"`` or ``"SR"``.
Returns:
ee.Image: The input image with an added ``"sensor"`` band (byte type) and
``"sensor"`` property.
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200101")
>>> with_sensor = addSensorBand(img, "C2_landsat", "SR")
"""
sensorDict = ee.Dictionary(
{
"LANDSAT_4": 4,
"LANDSAT_5": 5,
"LANDSAT_7": 7,
"LANDSAT_8": 8,
"LANDSAT_9": 9,
"Sentinel-2A": 21,
"Sentinel-2B": 22,
"Sentinel-2C": 23,
}
)
sensorPropDict = ee.Dictionary(
{
"C1_landsat": {"TOA": "SPACECRAFT_ID", "SR": "SATELLITE"},
"C2_landsat": {"TOA": "SPACECRAFT_ID", "SR": "SPACECRAFT_ID"},
"sentinel2": {"TOA": "SPACECRAFT_NAME", "SR": "SPACECRAFT_NAME"},
}
)
toaOrSR = toaOrSR.upper()
sensorProp = ee.Dictionary(sensorPropDict.get(whichProgram)).get(toaOrSR)
sensorName = img.get(sensorProp)
img = img.addBands(ee.Image.constant(sensorDict.get(sensorName)).rename(["sensor"]).byte()).set("sensor", sensorName)
return img
############################################################################
############################################################################
# Adds the float year with julian proportion to image
def addDateBand(img: ee.Image, maskTime: bool = False) -> ee.Image:
"""Adds a ``"year"`` band containing the fractional year (year + day-of-year fraction).
The band value is computed as ``year + fraction_of_year`` (e.g., 2020.5 for
approximately July 2, 2020).
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
maskTime (bool, optional): If ``True``, masks the date band to match the first
band's mask of the input image. Defaults to ``False``.
Returns:
ee.Image: The input image with an added ``"year"`` band (float).
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_date = addDateBand(img)
>>> with_masked_date = addDateBand(img, maskTime=True)
"""
d = ee.Date(img.get("system:time_start"))
y = d.get("year")
d = y.add(d.getFraction("year"))
# d=d.getFraction('year')
db = ee.Image.constant(d).rename(["year"]).float()
if maskTime:
db = db.updateMask(img.select([0]).mask())
return img.addBands(db)
def addYearFractionBand(img: ee.Image) -> ee.Image:
"""Adds a ``"year"`` band containing only the fractional part of the year (0 to 1).
Unlike :func:`addDateBand`, this does not include the integer year component.
A value of 0.5 corresponds to approximately July 2.
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
Returns:
ee.Image: The input image with an added ``"year"`` band (float, range 0--1).
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_frac = addYearFractionBand(img)
"""
d = ee.Date(img.get("system:time_start"))
y = d.get("year")
# d = y.add(d.getFraction('year'));
d = d.getFraction("year")
db = ee.Image.constant(d).rename(["year"]).float()
db = db # .updateMask(img.select([0]).mask())
return img.addBands(db)
def addYearYearFractionBand(img: ee.Image) -> ee.Image:
"""Adds a ``"year"`` band containing the full fractional year (year + fraction).
Functionally equivalent to :func:`addDateBand` with ``maskTime=False``, but
computed by explicitly adding the integer year and fractional year components.
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
Returns:
ee.Image: The input image with an added ``"year"`` band (float, e.g., 2020.5).
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_year_frac = addYearYearFractionBand(img)
"""
d = ee.Date(img.get("system:time_start"))
y = d.get("year")
# d = y.add(d.getFraction('year'));
d = d.getFraction("year")
db = ee.Image.constant(y).add(ee.Image.constant(d)).rename(["year"]).float()
db = db # .updateMask(img.select([0]).mask())
return img.addBands(db)
def addYearBand(img: ee.Image) -> ee.Image:
"""Adds a ``"year"`` band containing the integer year of the image acquisition.
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
Returns:
ee.Image: The input image with an added ``"year"`` band (float, e.g., 2020.0).
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_year = addYearBand(img)
"""
d = ee.Date(img.get("system:time_start"))
y = d.get("year")
db = ee.Image.constant(y).rename(["year"]).float()
db = db # .updateMask(img.select([0]).mask())
return img.addBands(db)
def addJulianDayBand(img: ee.Image) -> ee.Image:
"""Adds a ``"julianDay"`` band containing the day of the year (1--366).
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
Returns:
ee.Image: The input image with an added ``"julianDay"`` band (float).
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_julian = addJulianDayBand(img)
"""
d = ee.Date(img.get("system:time_start"))
julian = ee.Image(ee.Number.parse(d.format("DD"))).rename(["julianDay"])
return img.addBands(julian).float()
def addYearJulianDayBand(img: ee.Image) -> ee.Image:
"""Adds a ``"yearJulian"`` band encoding the 2-digit year and Julian day (YYDD).
The band value is a number in the format YYDD, where YY is the 2-digit year
and DD is the day of the year. For example, January 15, 2020 yields 2015.
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
Returns:
ee.Image: The input image with an added ``"yearJulian"`` band (float).
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200115")
>>> with_yj = addYearJulianDayBand(img)
"""
d = ee.Date(img.get("system:time_start"))
yj = ee.Image(ee.Number.parse(d.format("YYDD"))).rename(["yearJulian"])
return img.addBands(yj).float()
def addFullYearJulianDayBand(img: ee.Image) -> ee.Image:
"""Adds a ``"yearJulian"`` band encoding the full 4-digit year and Julian day (YYYYDD).
The band value is a number in the format YYYYDD, where YYYY is the 4-digit year
and DD is the day of the year. For example, July 1, 2020 yields 2020182.
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
Returns:
ee.Image: The input image with an added ``"yearJulian"`` band (int64, cast to float).
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> with_full_yj = addFullYearJulianDayBand(img)
"""
d = ee.Date(img.get("system:time_start"))
yj = ee.Image(ee.Number.parse(d.format("YYYYDD"))).rename(["yearJulian"]).int64()
return img.addBands(yj).float()
def offsetImageDate(img: ee.Image, n: int, unit: str) -> ee.Image:
"""Offsets the ``system:time_start`` property of an image by a specified amount.
Useful for shifting image dates when creating synthetic time series or aligning
images from different years.
Args:
img (ee.Image): The input Earth Engine image with a ``"system:time_start"`` property.
n (int): The number of units to offset. Can be negative to shift backward.
unit (str): The time unit for the offset. One of ``"year"``, ``"month"``,
``"week"``, ``"day"``, ``"hour"``, ``"minute"``, or ``"second"``.
Returns:
ee.Image: The image with its ``"system:time_start"`` property updated.
Examples:
>>> img = ee.Image("LANDSAT/LC08/C02/T1_L2/LC08_044034_20200701")
>>> shifted = offsetImageDate(img, -1, "year")
"""
date = ee.Date(img.get("system:time_start"))
date = date.advance(n, unit)
# date = ee.Date.fromYMD(100,date.get('month'),date.get('day'))
return img.set("system:time_start", date.millis())
################################################################
################################################################
fringeCountThreshold = 279 # Define number of non null observations for pixel to not be classified as a fringe
################################################################
# Kernel used for defringing
k = ee.Kernel.fixed(
41,
41,
[
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
],
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,