-
Notifications
You must be signed in to change notification settings - Fork 121
/
__init__.py
1192 lines (906 loc) · 43.1 KB
/
__init__.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
"""Toolbox for the ``ee.Image`` class."""
from __future__ import annotations
from typing import Optional, Union
import ee
import ee_extra
import ee_extra.Algorithms.core
from geetools.accessors import geetools_accessor
@geetools_accessor(ee.Image)
class Image:
"""Toolbox for the ``ee.Image`` class."""
def __init__(self, obj: ee.Image):
"""Initialize the Image class."""
self._obj = obj
# -- band manipulation -----------------------------------------------------
def addDate(self) -> ee.Image:
"""Add a band with the date of the image in the provided format.
The date is stored as a Timestamp in millisecond in a band "date".
Returns:
The image with the date band added.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image = image.geetools.addDate()
date = image.select('date')
buffer = ee.Geometry.Point([12.4534, 41.9033]).buffer(100)
value = date.reduceRegion(ee.Reducer.first(), buffer, 10).get("date")
ee.Date(value).format('YYYY-MM-dd').getInfo()
"""
date = self._obj.date().millis()
return self._obj.addBands(ee.Image.constant(date).rename("date"))
def addSuffix(
self, suffix: Union[str, ee.String], bands: Union[ee.List, list] = []
) -> ee.Image:
"""Add a suffix to the image selected band.
Add a suffix to the selected band. If no band is specified, the suffix is added to all bands.
Parameters:
suffix: The suffix to add to the band.
bands: The bands to add the suffix to. If None, all bands are selected.
Returns:
The image with the suffix added to the selected bands.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image = image.geetools.addSuffix('_suffix')
print(image.bandNames().getInfo())
"""
suffix = ee.String(suffix)
bands = self._obj.bandNames() if bands == [] else ee.List(bands)
bandNames = bands.iterate(
lambda b, n: ee.List(n).replace(b, ee.String(b).cat(suffix)),
self._obj.bandNames(),
)
return self._obj.rename(bandNames)
def addPrefix(
self, prefix: Union[str, ee.String], bands: Union[ee.List, list] = []
):
"""Add a prefix to the image selected band.
Add a prefix to the selected band. If no band is specified, the prefix is added to all bands.
Parameters:
prefix: The prefix to add to the band.
bands: The bands to add the prefix to. If None, all bands are selected.
Returns:
The image with the prefix added to the selected bands.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image = image.geetools.addPrefix('prefix_')
print(image.bandNames().getInfo())
"""
prefix = ee.String(prefix)
bands = self._obj.bandNames() if bands == [] else ee.List(bands)
bandNames = bands.iterate(
lambda b, n: ee.List(n).replace(b, prefix.cat(ee.String(b))),
self._obj.bandNames(),
)
return self._obj.rename(bandNames)
def rename(self, names: Union[ee.Dictionary, dict]) -> ee.Image:
"""Rename the bands of the image.
It's the same function as the one from GEE but it takes a dictionary as input.
Keys are the old names and values are the new names.
Parameters:
names: The new names of the bands.
Returns:
The image with the new band names.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
src = 'COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM'
image = ee.Image(src).select(['B1', 'B2', 'B3'])
image = image.geetools.rename({'B1': 'Aerosol', 'B2': 'Blue'})
print(image.bandNames().getInfo())
"""
names = ee.Dictionary(names)
bands = names.keys().iterate(
lambda b, n: ee.List(n).replace(b, names.get(b)), self._obj.bandNames()
)
return self._obj.rename(bands)
def remove(self, bands: Union[list, ee.List]) -> ee.Image:
"""Remove bands from the image.
Parameters:
bands: The bands to remove.
Returns:
The image without the specified bands.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
src = 'COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM'
image = ee.Image(src).select(['B1', 'B2', 'B3'])
image = image.geetools.remove(['B1', 'B2'])
print(image.bandNames().getInfo())
"""
bands = self._obj.bandNames().removeAll(ee.List(bands))
return self._obj.select(bands)
def doyToDate(
self,
year,
dateFormat: Union[str, ee.String] = "yyyyMMdd",
band: Union[ee.String, str] = "",
) -> ee.Image:
"""Convert the DOY band to a date band.
This method only work with date formats that can be converted to numbers as earthengine images don't accept string bands.
Args:
year: The year to use for the date
dateFormat: The date format to use for the date band
band: The band to use as DOY band. If empty, the first one is selected.
Returns:
The original image with the DOY band converted to a date band.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image.random().multiply(365).toInt()
vatican = ee.Geometry.Point([12.4534, 41.9033]).buffer(1)
image = image.geetools.doyToDate(2023)
print(image.reduceRegion(ee.Reducer.min(), vatican, 1).getInfo())
"""
year = ee.Number(year)
band = ee.String(band) if band else ee.String(self._obj.bandNames().get(0))
dateFormat = ee.String(dateFormat)
doyList = ee.List.sequence(0, 365)
remapList = doyList.map(
lambda d: ee.Number.parse(
ee.Date.fromYMD(year, 1, 1).advance(d, "day").format(dateFormat)
)
)
return self._obj.remap(doyList, remapList, bandName=band).rename(band)
# -- the rest --------------------------------------------------------------
def getValues(
self, point: ee.Geometry.Point, scale: Union[ee.Number, int] = 0
) -> ee.Dictionary:
"""Get the value of the image at the given point using specified geometry.
The result is presented as a dictionary where the keys are the bands name and the value the mean value of the band at the given point.
Parameters:
point: The geometry to get the value from.
Returns:
A dictionary with the band names and the value at the given point.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
point = ee.Geometry.Point([11.0, 45.0])
value = image.geetools.getValues(point, 10)
print(value.getInfo())
"""
scale = (
self._obj.select(0).projection().nominalScale()
if scale == 0
else ee.Number(scale)
)
return self._obj.reduceRegion(ee.Reducer.mean(), point, scale)
def minScale(self) -> ee.Number:
"""Return the minimum scale of the image.
It will be looking at all bands available so Select specific values before using this method.
Returns:
The minimum scale of the image.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image.geetools.minScale().getInfo()
"""
bandNames = self._obj.bandNames()
scales = bandNames.map(
lambda b: self._obj.select(ee.String(b)).projection().nominalScale()
)
return ee.Number(scales.sort().get(0))
def merge(self, images: Union[ee.List, list]) -> ee.Image:
"""Merge images into a single image.
Parameters:
images: The images to merge.
Returns:
The merged image.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image1 = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image2 = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQL')
image3 = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image = image1.geetools.merge([image2, image3])
print(image.bandNames().getInfo())
"""
images = ee.List(images)
merged = images.iterate(lambda dst, src: ee.Image(src).addBands(dst), self._obj)
return ee.Image(merged)
def toGrid(
self,
size: Union[ee.Number, int] = 1,
band: Union[str, ee.String] = "",
geometry: Optional[ee.Geometry] = None,
) -> ee.FeatureCollection:
"""Convert an image to a grid of polygons.
Based on the size given by the user, the tool will build a grid of size*pixelSize x size * pixelSize cells. Each cell will be a polygon. Note that for images that have multiple scale depending on the band, we will use the first one or the one stated in the parameters.
Parameters:
size: The size of the grid. It will be size * pixelSize x size * pixelSize cells.
band: The band to burn into the grid.
geometry: The geometry to use as reference for the grid. If None, the image footprint will be used.
Returns:
The grid as a FeatureCollection.
Note:
The method has a known bug when the projection of the image is different than 3857. As we use a buffer, the grid cells can slightly overlap. Feel free to open a Issue and contribute if you feel it needs improvements.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
src = 'COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM'
image = ee.Image(src)
buffer = ee.Geometry.Point([12.4534, 41.9033]).buffer(100)
grid = image.geetools.toGrid(1, 'B2', buffer)
print(grid.getInfo())
"""
band = ee.String(band) if band else self._obj.bandNames().get(0)
projection = self._obj.select(band).projection()
size = projection.nominalScale().multiply(ee.Number(size).toInt())
# extract the centers at the correct resolution
lonLat = ee.Image.pixelLonLat().reproject(projection)
coords = lonLat.reduceRegion(ee.Reducer.toList(), geometry, size)
# extract them as lists
lat, lon = ee.List(coords.get("latitude")), ee.List(coords.get("longitude"))
# we can now map them user their index to point -> buffer -> square
index = ee.List.sequence(0, lat.size().subtract(2))
squares = index.map(
lambda i: (
ee.Geometry.Point([lon.get(i), lat.get(i)])
.buffer(size.divide(2))
.bounds(0.01, projection)
)
)
# make the grid
features = ee.List(squares).map(lambda g: ee.Feature(ee.Geometry(g)))
return ee.FeatureCollection(features)
def clipOnCollection(
self, fc: ee.FeatureCollection, keepProperties: Union[ee.Number, int] = 1
) -> ee.ImageCollection:
"""Clip an image to a FeatureCollection.
The image will be clipped to every single features of the featureCollection as one independent image.
Parameters:
fc: The featureCollection to clip to.
keepProperties: If True, the properties of the featureCollection will be added to the clipped image.
Returns:
The clipped imageCollection.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
src = 'COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM'
image = ee.Image(src)
fc = ee.FeatureCollection('FAO/GAUL/2015/level0')
clipped = image.geetools.clipOnCollection(fc)
print(clipped.size().getInfo())
"""
def fcClip(feat):
image = self._obj.clip(feat.geometry())
return ee.Algorithms.If(
ee.Number(keepProperties).toInt(), image.copyProperties(feat), image
)
return ee.ImageCollection(fc.map(fcClip))
def bufferMask(
self,
radius: Union[int, ee.Number] = 1.5,
kernelType: Union[ee.String, str] = "square",
units: Union[ee.String, str] = "pixels",
) -> ee.Image:
"""Make a buffer around every masked pixel of the Image.
The buffer will be made using the specified radius, kernelType and units and will mask surrounfing pixels.
Parameters:
radius: The radius of the buffer.
kernelType: The kernel type of the buffer. One of: ``square``, ``circle``, ``diamond``, ``octagon``, ``plus``, ``square``.
units: The units of the radius. One of: ``pixels``, ``meters``.
Returns:
The image with the buffer mask applied.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
src = 'COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM'
image = ee.Image(src)
image = image.geetools.bufferMask(1.5, 'square', 'pixels')
print(image.bandNames().getInfo())
"""
radius, kernelType = ee.Number(radius), ee.String(kernelType)
units = ee.String(units)
masked = self._obj.mask().Not()
buffer = masked.focalMax(radius, kernelType, units)
return self._obj.updateMask(buffer.Not())
@classmethod
def full(
self,
values: Union[list, ee.List] = [0],
names: Union[list, ee.List] = ["constant"],
) -> ee.Image:
"""Create an image with the given values and names.
Parameters:
values: The values to initialize the image with. If one value is given, it will be used for all bands.
names: The names of the bands. By default it uses the earthen engine default value, "constant".
Returns:
An image with the given values and names.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image.geetools.full([1, 2, 3], ['a', 'b', 'c'])
print(image.bandNames().getInfo())
"""
values, names = ee.List(values), ee.List(names)
# resize value to the same length as names
values = ee.List(
ee.Algorithms.If(
values.size().eq(1),
ee.List.repeat(ee.Number(values.get(0)), names.size()),
values,
)
)
return ee.Image.constant(values).rename(names)
def fullLike(
self,
fillValue: Union[int, float, ee.Number],
copyProperties: Union[ee.Number, int] = 0,
keepMask: Union[ee.Number, int] = 0,
) -> ee.Image:
"""Create an image with the same band names, projection and scale as the original image.
The projection is computed on the first band, make sure all bands have the same.
The procduced image can also copy the properties of the original image and keep the mask.
Parameters:
fillValue: The value to fill the image with.
copyProperties: If True, the properties of the original image will be copied to the new one.
keepMask: If True, the mask of the original image will be copied to the new one.
Returns:
An image with the same band names, projection and scale as the original image.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image = image.geetools.fullLike(0)
print(image.bandNames().getInfo())
"""
keepMask, copyProperties = ee.Number(keepMask), ee.Number(copyProperties)
footprint, bandNames = self._obj.geometry(), self._obj.bandNames()
fillValue = ee.List.repeat(fillValue, bandNames.size())
image = (
self.full(fillValue, bandNames)
.reproject(self._obj.select(0).projection())
.clip(footprint)
)
withProperties = image.copyProperties(self._obj)
image = ee.Algorithms.If(copyProperties, withProperties, image)
withMask = ee.Image(image).updateMask(self._obj.mask())
image = ee.Algorithms.If(keepMask, withMask, image)
return ee.Image(image)
def reduceBands(
self,
reducer: Union[str, ee.String],
bands: Union[list, ee.List] = [],
name: Union[str, ee.String] = "",
) -> ee.Image:
"""Reduce the image using the selected reducer and adding the result as a band using the selected name.
Args:
bands: The bands to reduce
reducer: The reducer to use
name: The name of the new band
Returns:
The image with the new reduced band added
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
image = image.geetools.reduceBands("mean", ['B1', 'B2'])
print(image.bandNames().getInfo())
"""
# the reduce method only accept client side string
if not isinstance(reducer, str):
raise TypeError("reducer must be a Python string")
bands, name = ee.List(bands), ee.String(name)
bands = ee.Algorithms.If(bands.size().eq(0), self._obj.bandNames(), bands)
name = ee.Algorithms.If(name.equals(ee.String("")), reducer, name)
reduceImage = self._obj.select(ee.List(bands)).reduce(reducer).rename([name])
return self._obj.addBands(reduceImage)
def negativeClip(
self, geometry: Union[ee.FeatureCollection, ee.Geometry]
) -> ee.Image:
"""The opposite of the clip method.
The inside of the geometry will be masked from the image.
Args:
geometry: The geometry to mask from the image.
Returns:
The image with the geometry masked.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
src, bands = "COPERNICUS/S2_SR_HARMONIZED", ["B1", "B2", "B3"]
vatican = ee.Geometry.Point([12.4534, 41.9033]).buffer(1)
image = ee.ImageCollection(src).filterBounds(vatican).first().select(bands)
image = image.geetools.negativeClip(vatican)
print(image.reduceRegion(ee.Reducer.mean(), vatican, 1).getInfo())
"""
return self._obj.updateMask(self._obj.clip(geometry).mask().Not())
def format(
self,
string: Union[str, ee.String],
dateFormat: Union[str, ee.String] = "yyyy-MM-dd",
) -> ee.String:
"""Create a string from using the given pattern and using the image properties.
The ``system_date`` property is special cased to fit the dateFormat parameter.
Args:
string: The pattern to use for the string
dateFormat: The date format to use for the system_date property
Returns:
The string corresponding to the image
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR_HARMONIZED/20200101T100319_20200101T100321_T32TQM')
string = image.geetools.format('this is the image date: {system_date}')
print(string.getInfo())
"""
dateFormat, string = ee.String(dateFormat), ee.String(string)
patternList = string.match(r"\{([^}]+)\}", "g")
def replaceProperties(p, s):
p = ee.String(p)
prop = self._obj.get(p.slice(1, -1))
date = self._obj.date().format(dateFormat)
prop = ee.Algorithms.If(p.equals("{system_date}"), date, prop)
# return ee.String(s).cat(date)
return ee.String(s).replace(p, ee.String(prop))
return patternList.iterate(replaceProperties, string)
def gauss(self, band: Union[ee.String, str] = "") -> ee.Image:
"""Apply a gaussian filter to the image.
We apply the following function to the image: "exp(((val-mean)**2)/(-2*(std**2)))"
where val is the value of the pixel, mean is the mean of the image, std is the standard deviation of the image.
See the `Gaussian filter <https://en.wikipedia.org/wiki/Gaussian_function>`_ Wikipedia page for more information.
Args:
band: The band to apply the gaussian filter to. If empty, the first one is selected.
Returns:
The image with the gaussian filter applied.An single band image with the gaussian filter applied.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED").first()
image = image.geetools.gauss()
print(image.bandNames().getInfo())
"""
band = ee.String(band) if band else ee.String(self._obj.bandNames().get(0))
image = self._obj.select(band)
kwargs = {"geometry": image.geometry(), "bestEffort": True}
mean = image.reduceRegion(ee.Reducer.mean(), **kwargs).get(band)
std = image.reduceRegion(ee.Reducer.stdDev(), **kwargs).get(band)
return image.expression(
"exp(((val-mean)**2)/(-2*(std**2)))",
{
"val": image,
"mean": ee.Image.constant(mean),
"std": ee.Image.constant(std),
},
).rename(band.cat("_gauss"))
def repeat(self, band, repeats: Union[ee.Number, int]) -> ee.image:
"""Repeat a band of the image.
Args:
band: The band to repeat
repeats: The number of times to repeat the band
Returns:
The image with the band repeated
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED").first()
image = image.geetools.repeat('B1', 2)
print(image.bandNames().getInfo())
"""
band, repeats = ee.String(band), ee.Number(repeats).toInt()
sequence = ee.List.sequence(1, repeats)
image = self._obj.select(band)
def addBand(n, i):
name = band.cat("_").cat(ee.Number(n).toInt().format())
return ee.Image(i).addBands(image.rename(name))
return ee.Image(sequence.iterate(addBand, self._obj))
def removeZeros(self) -> ee.Image:
"""Return an image array with non-zero values extracted from each band.
This function processes a multi-band image array, where each band represents different data.
It removes zero values from each band independently and then combines the non-zero values from all bands into a single image.
The resulting image may have inconsistent array lengths for each pixel, as the number of zero values removed can vary across bands.
Returns:
The image with the zero values removed from each band.
Example:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
vatican = ee.Geometry.Point([12.4534, 41.9033]).buffer(1)
image = ee.Image([0, 1, 2]).toArray()
image = image.geetools.removeZeros()
values = image.reduceRegion(ee.Reducer.first(), vatican, 1)
print(values.getInfo())
"""
bands = self._obj.bandNames()
def remove(band):
image = self._obj.select([band])
isZero = image.divide(image)
countZeros = isZero.arrayReduce(ee.Reducer.sum(), [0]).multiply(-1)
nbZeros = countZeros.arrayProject([0]).arrayFlatten([["n"]]).toInt()
return image.arraySort().arraySlice(0, nbZeros)
return ee.ImageCollection(bands.map(remove)).toBands().rename(bands)
def interpolateBands(
self, src: Union[list, ee.List], to: Union[list, ee.List]
) -> ee.Image:
"""Interpolate bands from the "src" value range to the "to" value range.
The Interpolation is performed linearly using the "extrapolate" option of the "interpolate" method.
Args:
src: The source value range
to: The target value range
Returns:
The image with the interpolated bands
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
vatican = ee.Geometry.Point([12.4534, 41.9033]).buffer(1)
image = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED').filterBounds(vatican).first()
image = image.select(["B4", "B3", "B2"]).geetools.interpolateBands([0, 3000], [0, 30])
values = image.reduceRegion(ee.Reducer.mean(), vatican, 1)
print(values.getInfo())
"""
bands = self._obj.bandNames()
src, to = ee.List(src), ee.List(to)
def interpolate(band):
original = self._obj.select([band])
normalized = original.unitScale(src.get(0), src.get(1))
return normalized.interpolate([0, 1], to)
return ee.ImageCollection(bands.map(interpolate)).toBands().rename(bands)
def isletMask(self, offset: Union[ee.Number, float, int]) -> ee.Image:
"""Compute the islet mask from an image.
An islet is a set of non-masked pixels connected together by their edges of very small surface. The user define the offset of the island size and we compute the max number of pixels to improve computation speed. The inpt Image needs to be a single band binary image.
Args:
offset: The limit of the islet size in square metters
Returns:
The island mask
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED").first()
mask = image.select('SCL').eq(4)
mask = mask.geetools.islandMask(100)
print(mask.bandNames().getInfo())
"""
offset = ee.Number(offset)
scale = self._obj.projection().nominalScale()
pixelsLimit = offset.multiply(2).sqrt().divide(scale).max(ee.Number(2)).toInt()
area = ee.Image.pixelArea().rename("area")
isletArea = (
self._obj.select(0)
.mask()
.toInt()
.connectedPixelCount(pixelsLimit)
.multiply(area)
)
return isletArea.lt(offset).rename("mask").selfMask()
# -- ee-extra wrapper ------------------------------------------------------
def index_list(cls) -> dict:
"""Return the list of indices implemented in this module.
Returns:
List of indices implemented in this module
Examples:
.. jupyter-execute::
import ee, geetools
ind = ee.Image.geetools.indices()["BAIS2"]
print(ind["long_name"])
print(ind["formula"])
print(ind["reference"])
"""
return ee_extra.Spectral.core.indices()
def spectralIndices(
self,
index: str = "NDVI",
G: Union[float, int] = 2.5,
C1: Union[float, int] = 6.0,
C2: Union[float, int] = 7.5,
L: Union[float, int] = 1.0,
cexp: Union[float, int] = 1.16,
nexp: Union[float, int] = 2.0,
alpha: Union[float, int] = 0.1,
slope: Union[float, int] = 1.0,
intercept: Union[float, int] = 0.0,
gamma: Union[float, int] = 1.0,
omega: Union[float, int] = 2.0,
beta: Union[float, int] = 0.05,
k: Union[float, int] = 0.0,
fdelta: Union[float, int] = 0.581,
kernel: str = "RBF",
sigma: str = "0.5 * (a + b)",
p: Union[float, int] = 2.0,
c: Union[float, int] = 1.0,
lambdaN: Union[float, int] = 858.5,
lambdaR: Union[float, int] = 645.0,
lambdaG: Union[float, int] = 555.0,
online: Union[float, int] = False,
) -> ee.Image:
"""Computes one or more spectral indices (indices are added as bands) for an image from the Awesome List of Spectral Indices.
Parameters:
self: Image to compute indices on. Must be scaled to [0,1].
index: Index or list of indices to compute, default = 'NDVI'
Available options:
- 'vegetation' : Compute all vegetation indices.
- 'burn' : Compute all burn indices.
- 'water' : Compute all water indices.
- 'snow' : Compute all snow indices.
- 'urban' : Compute all urban (built-up) indices.
- 'kernel' : Compute all kernel indices.
- 'all' : Compute all indices listed below.
- Awesome Spectral Indices for GEE: Check the complete list of indices `here <https://awesome-ee-spectral-indices.readthedocs.io/en/latest/list.html>`_.
G: Gain factor. Used just for index = 'EVI', default = 2.5
C1: Coefficient 1 for the aerosol resistance term. Used just for index = 'EVI', default = 6.0
C2: Coefficient 2 for the aerosol resistance term. Used just for index = 'EVI', default = 7.5
L: Canopy background adjustment. Used just for index = ['EVI','SAVI'], default = 1.0
cexp: Exponent used for OCVI, default = 1.16
nexp: Exponent used for GDVI, default = 2.0
alpha: Weighting coefficient used for WDRVI, default = 0.1
slope: Soil line slope, default = 1.0
intercept: Soil line intercept, default = 0.0
gamma: Weighting coefficient used for ARVI, default = 1.0
omega: Weighting coefficient used for MBWI, default = 2.0
beta: Calibration parameter used for NDSIns, default = 0.05
k: Slope parameter by soil used for NIRvH2, default = 0.0
fdelta: Adjustment factor used for SEVI, default = 0.581
kernel: Kernel used for kernel indices, default = 'RBF'
Available options:
- 'linear' : Linear Kernel.
- 'RBF' : Radial Basis Function (RBF) Kernel.
- 'poly' : Polynomial Kernel.
sigma: Length-scale parameter. Used for kernel = 'RBF', default = '0.5 * (a + b)'. If str, this must be an expression including 'a' and 'b'. If numeric, this must be positive.
p: Kernel degree. Used for kernel = 'poly', default = 2.0
c: Free parameter that trades off the influence of higher-order versus lower-order terms in the polynomial kernel. Used for kernel = 'poly', default = 1.0. This must be greater than or equal to 0.
lambdaN: NIR wavelength used for NIRvH2 and NDGI, default = 858.5
lambdaR: Red wavelength used for NIRvH2 and NDGI, default = 645.0
lambdaG: Green wavelength used for NDGI, default = 555.0
drop: Whether to drop all bands except the new spectral indices, default = False
Returns:
Image with the computed spectral index, or indices, as new bands.
Examples:
.. jupyter-execute::
import ee, geetools
ee.Initialize()
image = ee.Image('COPERNICUS/S2_SR/20190828T151811_20190828T151809_T18GYT')
image = image.specralIndices(["NDVI", "NDFI"])
"""
# fmt: off
return ee_extra.Spectral.core.spectralIndices(
self._obj, index, G, C1, C2, L, cexp, nexp, alpha, slope, intercept, gamma, omega,
beta, k, fdelta, kernel, sigma, p, c, lambdaN, lambdaR, lambdaG, online,
drop=False,
)
# fmt: on
def getScaleParams(self) -> dict:
"""Gets the scale parameters for each band of the image.
Returns:
Dictionary with the scale parameters for each band.
Examples:
.. jupyter-execute::
import ee
import geetools
ee.Initialize()
ee.ImageCollection('MODIS/006/MOD11A2').first().geetools.getScaleParams()
"""
return ee_extra.STAC.core.getScaleParams(self._obj)
def getOffsetParams(self) -> dict:
"""Gets the offset parameters for each band of the image.
Returns:
Dictionary with the offset parameters for each band.
Examples:
.. jupyter-execute::
import ee
import geetools
ee.Initialize()
ee.ImageCollection('MODIS/006/MOD11A2').first().getOffsetParams()
"""
return ee_extra.STAC.core.getOffsetParams(self._obj)
def scaleAndOffset(self) -> ee.Image:
"""Scales bands on an image according to their scale and offset parameters.
Returns:
Scaled image.
Examples:
.. jupyter_execute::
import ee, geetools
ee.Initialize()
S2 = ee.ImageCollection('COPERNICUS/S2_SR').first().scaleAndOffset()
"""
return ee_extra.STAC.core.scaleAndOffset(self._obj)
def preprocess(self, **kwargs) -> ee.Image:
"""Pre-processes the image: masks clouds and shadows, and scales and offsets the image.
Parameters:
**kwargs: Keywords arguments for ``maskClouds`` method.
Returns:
Pre-processed image.
Examples:
.. jupyter-execute::
import ee
import geetools
ee.Initialize()
S2 = ee.ImageCollection('COPERNICUS/S2_SR').first().preprocess()
"""
return ee_extra.QA.pipelines.preprocess(self._obj, **kwargs)
def getSTAC(self) -> dict:
"""Gets the STAC of the image.
Returns:
STAC of the image.
Examples:
.. jupyter-execute::
import ee
import geetools
ee.Initialize()
ee.ImageCollection('COPERNICUS/S2_SR').first().getSTAC()
"""
return ee_extra.STAC.core.getSTAC(self._obj)
def getDOI(self) -> str:
"""Gets the DOI of the image, if available.
Returns:
DOI of the ee.Image dataset.
Examples:
.. jupyter-execute::