/
common.py
15444 lines (12515 loc) · 525 KB
/
common.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
"""This module contains some common functions for both folium and ipyleaflet to interact with the Earth Engine Python API.
"""
# *******************************************************************************#
# This module contains core features and extra features of the geemap package. #
# The Earth Engine team and the geemap community will maintain the core features.#
# The geemap community will maintain the extra features. #
# The core features include classes and functions below until the line # ******* #
# *******************************************************************************#
import csv
import datetime
import io
import json
import math
import os
import requests
import shutil
import tarfile
import urllib.request
import warnings
import zipfile
import ee
import ipywidgets as widgets
from ipytree import Node, Tree
try:
from IPython.display import display, IFrame
except ImportError:
pass
def ee_initialize(
token_name="EARTHENGINE_TOKEN",
auth_mode="notebook",
service_account=False,
auth_args={},
**kwargs,
):
"""Authenticates Earth Engine and initialize an Earth Engine session
Args:
token_name (str, optional): The name of the Earth Engine token. Defaults to "EARTHENGINE_TOKEN".
auth_mode (str, optional): The authentication mode, can be one of paste,notebook,gcloud,appdefault. Defaults to "notebook".
service_account (bool, optional): If True, use a service account. Defaults to False.
auth_args (dict, optional): Additional authentication parameters for aa.Authenticate(). Defaults to {}.
kwargs (dict, optional): Additional parameters for ee.Initialize(). For example,
opt_url='https://earthengine-highvolume.googleapis.com' to use the Earth Engine High-Volume platform. Defaults to {}.
"""
import httplib2
from .__init__ import __version__
user_agent = f"geemap/{__version__}"
if "http_transport" not in kwargs:
kwargs["http_transport"] = httplib2.Http()
auth_args["auth_mode"] = auth_mode
if ee.data._credentials is None:
ee_token = os.environ.get(token_name)
if service_account:
try:
credential_file_path = os.path.expanduser(
"~/.config/earthengine/private-key.json"
)
if os.path.exists(credential_file_path):
with open(credential_file_path) as f:
token_dict = json.load(f)
else:
token_name = "EARTHENGINE_TOKEN"
ee_token = os.environ.get(token_name)
token_dict = json.loads(ee_token, strict=False)
service_account = token_dict["client_email"]
private_key = token_dict["private_key"]
credentials = ee.ServiceAccountCredentials(
service_account, key_data=private_key
)
ee.Initialize(credentials, **kwargs)
except Exception as e:
raise Exception(e)
else:
try:
if ee_token is not None:
credential_file_path = os.path.expanduser(
"~/.config/earthengine/credentials"
)
if not os.path.exists(credential_file_path):
os.makedirs(
os.path.dirname(credential_file_path), exist_ok=True
)
if ee_token.startswith("{") and ee_token.endswith(
"}"
): # deals with token generated by new auth method (earthengine-api>=0.1.304).
token_dict = json.loads(ee_token)
with open(credential_file_path, "w") as f:
f.write(json.dumps(token_dict))
else:
credential = (
'{"refresh_token":"%s"}' % ee_token
) # deals with token generated by old auth method.
with open(credential_file_path, "w") as f:
f.write(credential)
elif in_colab_shell():
if credentials_in_drive() and (not credentials_in_colab()):
copy_credentials_to_colab()
elif not credentials_in_colab:
ee.Authenticate(**auth_args)
if is_drive_mounted() and (not credentials_in_drive()):
copy_credentials_to_drive()
else:
if is_drive_mounted():
copy_credentials_to_drive()
ee.Initialize(**kwargs)
except Exception:
ee.Authenticate(**auth_args)
ee.Initialize(**kwargs)
ee.data.setUserAgent(user_agent)
def ee_export_image(
ee_object,
filename,
scale=None,
crs=None,
crs_transform=None,
region=None,
dimensions=None,
file_per_band=False,
format="ZIPPED_GEO_TIFF",
unzip=True,
unmask_value=None,
timeout=300,
proxies=None,
):
"""Exports an ee.Image as a GeoTIFF.
Args:
ee_object (object): The ee.Image to download.
filename (str): Output filename for the exported image.
scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specified. Defaults to None.
crs (str, optional): A default CRS string to use for any bands that do not explicitly specify one. Defaults to None.
crs_transform (list, optional): a default affine transform to use for any bands that do not specify one, of the same format as the crs_transform of bands. Defaults to None.
region (object, optional): A polygon specifying a region to download; ignored if crs and crs_transform is specified. Defaults to None.
dimensions (list, optional): An optional array of two integers defining the width and height to which the band is cropped. Defaults to None.
file_per_band (bool, optional): Whether to produce a different GeoTIFF per band. Defaults to False.
format (str, optional): One of: "ZIPPED_GEO_TIFF" (GeoTIFF file(s) wrapped in a zip file, default), "GEO_TIFF" (GeoTIFF file), "NPY" (NumPy binary format). If "GEO_TIFF" or "NPY",
filePerBand and all band-level transformations will be ignored. Loading a NumPy output results in a structured array.
unzip (bool, optional): Whether to unzip the downloaded file. Defaults to True.
unmask_value (float, optional): The value to use for pixels that are masked in the input image.
If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None.
timeout (int, optional): The timeout in seconds for the request. Defaults to 300.
proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None.
"""
if not isinstance(ee_object, ee.Image):
print("The ee_object must be an ee.Image.")
return
if unmask_value is not None:
ee_object = ee_object.selfMask().unmask(unmask_value)
if isinstance(region, ee.Geometry):
ee_object = ee_object.clip(region)
elif isinstance(region, ee.FeatureCollection):
ee_object = ee_object.clipToCollection(region)
filename = os.path.abspath(filename)
basename = os.path.basename(filename)
name = os.path.splitext(basename)[0]
filetype = os.path.splitext(basename)[1][1:].lower()
filename_zip = filename.replace(".tif", ".zip")
if filetype != "tif":
print("The filename must end with .tif")
return
try:
print("Generating URL ...")
params = {"name": name, "filePerBand": file_per_band}
params["scale"] = scale
if region is None:
region = ee_object.geometry()
if dimensions is not None:
params["dimensions"] = dimensions
if region is not None:
params["region"] = region
if crs is not None:
params["crs"] = crs
if crs_transform is not None:
params["crs_transform"] = crs_transform
if format != "ZIPPED_GEO_TIFF":
params["format"] = format
try:
url = ee_object.getDownloadURL(params)
except Exception as e:
print("An error occurred while downloading.")
print(e)
return
print(f"Downloading data from {url}\nPlease wait ...")
# Need to initialize r to something because of how we currently handle errors
# We should aim to refactor the code such that only one try block is needed
r = None
r = requests.get(url, stream=True, timeout=timeout, proxies=proxies)
if r.status_code != 200:
print("An error occurred while downloading.")
return
with open(filename_zip, "wb") as fd:
for chunk in r.iter_content(chunk_size=1024):
fd.write(chunk)
except Exception as e:
print("An error occurred while downloading.")
if r is not None:
print(r.json()["error"]["message"])
return
try:
if unzip:
with zipfile.ZipFile(filename_zip) as z:
z.extractall(os.path.dirname(filename))
os.remove(filename_zip)
if file_per_band:
print(f"Data downloaded to {os.path.dirname(filename)}")
else:
print(f"Data downloaded to {filename}")
except Exception as e:
print(e)
def ee_export_image_collection(
ee_object,
out_dir,
scale=None,
crs=None,
crs_transform=None,
region=None,
dimensions=None,
file_per_band=False,
format="ZIPPED_GEO_TIFF",
unmask_value=None,
filenames=None,
timeout=300,
proxies=None,
):
"""Exports an ImageCollection as GeoTIFFs.
Args:
ee_object (object): The ee.Image to download.
out_dir (str): The output directory for the exported images.
scale (float, optional): A default scale to use for any bands that do not specify one; ignored if crs and crs_transform is specified. Defaults to None.
crs (str, optional): A default CRS string to use for any bands that do not explicitly specify one. Defaults to None.
crs_transform (list, optional): a default affine transform to use for any bands that do not specify one, of the same format as the crs_transform of bands. Defaults to None.
region (object, optional): A polygon specifying a region to download; ignored if crs and crs_transform is specified. Defaults to None.
dimensions (list, optional): An optional array of two integers defining the width and height to which the band is cropped. Defaults to None.
file_per_band (bool, optional): Whether to produce a different GeoTIFF per band. Defaults to False.
format (str, optional): One of: "ZIPPED_GEO_TIFF" (GeoTIFF file(s) wrapped in a zip file, default), "GEO_TIFF" (GeoTIFF file), "NPY" (NumPy binary format). If "GEO_TIFF" or "NPY",
filePerBand and all band-level transformations will be ignored. Loading a NumPy output results in a structured array.
unmask_value (float, optional): The value to use for pixels that are masked in the input image.
If the exported image contains zero values, you should set the unmask value to a non-zero value so that the zero values are not treated as missing data. Defaults to None.
filenames (list | int, optional): A list of filenames to use for the exported images. Defaults to None.
timeout (int, optional): The timeout in seconds for the request. Defaults to 300.
proxies (dict, optional): A dictionary of proxy servers to use. Defaults to None.
"""
if not isinstance(ee_object, ee.ImageCollection):
print("The ee_object must be an ee.ImageCollection.")
return
if not os.path.exists(out_dir):
os.makedirs(out_dir)
try:
count = int(ee_object.size().getInfo())
print(f"Total number of images: {count}\n")
if filenames is None:
filenames = ee_object.aggregate_array("system:index").getInfo()
elif isinstance(filenames, int):
filenames = [str(f + filenames) for f in range(0, count)]
if len(filenames) != count:
raise Exception(
"The number of filenames must be equal to the number of images."
)
filenames = [str(f) + ".tif" for f in filenames if not str(f).endswith(".tif")]
for i in range(0, count):
image = ee.Image(ee_object.toList(count).get(i))
filename = os.path.join(out_dir, filenames[i])
print(f"Exporting {i + 1}/{count}: {filename}")
ee_export_image(
image,
filename=filename,
scale=scale,
crs=crs,
crs_transform=crs_transform,
region=region,
dimensions=dimensions,
file_per_band=file_per_band,
format=format,
unmask_value=unmask_value,
timeout=timeout,
proxies=proxies,
)
print("\n")
except Exception as e:
print(e)
def ee_export_image_to_drive(
image,
description="myExportImageTask",
folder=None,
fileNamePrefix=None,
dimensions=None,
region=None,
scale=None,
crs=None,
crsTransform=None,
maxPixels=None,
shardSize=None,
fileDimensions=None,
skipEmptyTiles=None,
fileFormat=None,
formatOptions=None,
**kwargs,
):
"""Creates a batch task to export an Image as a raster to Google Drive.
Args:
image: The image to be exported.
description: Human-readable name of the task.
folder: The name of a unique folder in your Drive account to
export into. Defaults to the root of the drive.
fileNamePrefix: The Google Drive filename for the export.
Defaults to the name of the task.
dimensions: The dimensions of the exported image. Takes either a
single positive integer as the maximum dimension or "WIDTHxHEIGHT"
where WIDTH and HEIGHT are each positive integers.
region: The lon,lat coordinates for a LinearRing or Polygon
specifying the region to export. Can be specified as a nested
lists of numbers or a serialized string. Defaults to the image's
region.
scale: The resolution in meters per pixel. Defaults to the
native resolution of the image assset unless a crsTransform
is specified.
crs: The coordinate reference system of the exported image's
projection. Defaults to the image's default projection.
crsTransform: A comma-separated string of 6 numbers describing
the affine transform of the coordinate reference system of the
exported image's projection, in the order: xScale, xShearing,
xTranslation, yShearing, yScale and yTranslation. Defaults to
the image's native CRS transform.
maxPixels: The maximum allowed number of pixels in the exported
image. The task will fail if the exported region covers more
pixels in the specified projection. Defaults to 100,000,000.
shardSize: Size in pixels of the tiles in which this image will be
computed. Defaults to 256.
fileDimensions: The dimensions in pixels of each image file, if the
image is too large to fit in a single file. May specify a
single number to indicate a square shape, or a tuple of two
dimensions to indicate (width,height). Note that the image will
still be clipped to the overall image dimensions. Must be a
multiple of shardSize.
skipEmptyTiles: If true, skip writing empty (i.e. fully-masked)
image tiles. Defaults to false.
fileFormat: The string file format to which the image is exported.
Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to
'GeoTIFF'.
formatOptions: A dictionary of string keys to format specific options.
**kwargs: Holds other keyword arguments that may have been deprecated
such as 'crs_transform', 'driveFolder', and 'driveFileNamePrefix'.
"""
if not isinstance(image, ee.Image):
raise ValueError("Input image must be an instance of ee.Image")
task = ee.batch.Export.image.toDrive(
image,
description,
folder,
fileNamePrefix,
dimensions,
region,
scale,
crs,
crsTransform,
maxPixels,
shardSize,
fileDimensions,
skipEmptyTiles,
fileFormat,
formatOptions,
**kwargs,
)
task.start()
def ee_export_image_to_asset(
image,
description="myExportImageTask",
assetId=None,
pyramidingPolicy=None,
dimensions=None,
region=None,
scale=None,
crs=None,
crsTransform=None,
maxPixels=None,
**kwargs,
):
"""Creates a task to export an EE Image to an EE Asset.
Args:
image: The image to be exported.
description: Human-readable name of the task.
assetId: The destination asset ID.
pyramidingPolicy: The pyramiding policy to apply to each band in the
image, a dictionary keyed by band name. Values must be
one of: "mean", "sample", "min", "max", or "mode".
Defaults to "mean". A special key, ".default", may be used to
change the default for all bands.
dimensions: The dimensions of the exported image. Takes either a
single positive integer as the maximum dimension or "WIDTHxHEIGHT"
where WIDTH and HEIGHT are each positive integers.
region: The lon,lat coordinates for a LinearRing or Polygon
specifying the region to export. Can be specified as a nested
lists of numbers or a serialized string. Defaults to the image's
region.
scale: The resolution in meters per pixel. Defaults to the
native resolution of the image assset unless a crsTransform
is specified.
crs: The coordinate reference system of the exported image's
projection. Defaults to the image's default projection.
crsTransform: A comma-separated string of 6 numbers describing
the affine transform of the coordinate reference system of the
exported image's projection, in the order: xScale, xShearing,
xTranslation, yShearing, yScale and yTranslation. Defaults to
the image's native CRS transform.
maxPixels: The maximum allowed number of pixels in the exported
image. The task will fail if the exported region covers more
pixels in the specified projection. Defaults to 100,000,000.
**kwargs: Holds other keyword arguments that may have been deprecated
such as 'crs_transform'.
"""
if isinstance(image, ee.Image) or isinstance(image, ee.image.Image):
pass
else:
raise ValueError("Input image must be an instance of ee.Image")
if isinstance(assetId, str):
if assetId.startswith("users/") or assetId.startswith("projects/"):
pass
else:
assetId = f"{ee_user_id()}/{assetId}"
task = ee.batch.Export.image.toAsset(
image,
description,
assetId,
pyramidingPolicy,
dimensions,
region,
scale,
crs,
crsTransform,
maxPixels,
**kwargs,
)
task.start()
def ee_export_image_to_cloud_storage(
image,
description="myExportImageTask",
bucket=None,
fileNamePrefix=None,
dimensions=None,
region=None,
scale=None,
crs=None,
crsTransform=None,
maxPixels=None,
shardSize=None,
fileDimensions=None,
skipEmptyTiles=None,
fileFormat=None,
formatOptions=None,
**kwargs,
):
"""Creates a task to export an EE Image to Google Cloud Storage.
Args:
image: The image to be exported.
description: Human-readable name of the task.
bucket: The name of a Cloud Storage bucket for the export.
fileNamePrefix: Cloud Storage object name prefix for the export.
Defaults to the name of the task.
dimensions: The dimensions of the exported image. Takes either a
single positive integer as the maximum dimension or "WIDTHxHEIGHT"
where WIDTH and HEIGHT are each positive integers.
region: The lon,lat coordinates for a LinearRing or Polygon
specifying the region to export. Can be specified as a nested
lists of numbers or a serialized string. Defaults to the image's
region.
scale: The resolution in meters per pixel. Defaults to the
native resolution of the image assset unless a crsTransform
is specified.
crs: The coordinate reference system of the exported image's
projection. Defaults to the image's default projection.
crsTransform: A comma-separated string of 6 numbers describing
the affine transform of the coordinate reference system of the
exported image's projection, in the order: xScale, xShearing,
xTranslation, yShearing, yScale and yTranslation. Defaults to
the image's native CRS transform.
maxPixels: The maximum allowed number of pixels in the exported
image. The task will fail if the exported region covers more
pixels in the specified projection. Defaults to 100,000,000.
shardSize: Size in pixels of the tiles in which this image will be
computed. Defaults to 256.
fileDimensions: The dimensions in pixels of each image file, if the
image is too large to fit in a single file. May specify a
single number to indicate a square shape, or a tuple of two
dimensions to indicate (width,height). Note that the image will
still be clipped to the overall image dimensions. Must be a
multiple of shardSize.
skipEmptyTiles: If true, skip writing empty (i.e. fully-masked)
image tiles. Defaults to false.
fileFormat: The string file format to which the image is exported.
Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to
'GeoTIFF'.
formatOptions: A dictionary of string keys to format specific options.
**kwargs: Holds other keyword arguments that may have been deprecated
such as 'crs_transform'.
"""
if not isinstance(image, ee.Image):
raise ValueError("Input image must be an instance of ee.Image")
try:
task = ee.batch.Export.image.toCloudStorage(
image,
description,
bucket,
fileNamePrefix,
dimensions,
region,
scale,
crs,
crsTransform,
maxPixels,
shardSize,
fileDimensions,
skipEmptyTiles,
fileFormat,
formatOptions,
**kwargs,
)
task.start()
except Exception as e:
print(e)
def ee_export_image_collection_to_drive(
ee_object,
descriptions=None,
folder=None,
fileNamePrefix=None,
dimensions=None,
region=None,
scale=None,
crs=None,
crsTransform=None,
maxPixels=None,
shardSize=None,
fileDimensions=None,
skipEmptyTiles=None,
fileFormat=None,
formatOptions=None,
**kwargs,
):
"""Creates a batch task to export an ImageCollection as raster images to Google Drive.
Args:
ee_object: The image collection to export.
descriptions: A list of human-readable names of the tasks.
folder: The name of a unique folder in your Drive account to
export into. Defaults to the root of the drive.
fileNamePrefix: The Google Drive filename for the export.
Defaults to the name of the task.
dimensions: The dimensions of the exported image. Takes either a
single positive integer as the maximum dimension or "WIDTHxHEIGHT"
where WIDTH and HEIGHT are each positive integers.
region: The lon,lat coordinates for a LinearRing or Polygon
specifying the region to export. Can be specified as a nested
lists of numbers or a serialized string. Defaults to the image's
region.
scale: The resolution in meters per pixel. Defaults to the
native resolution of the image assset unless a crsTransform
is specified.
crs: The coordinate reference system of the exported image's
projection. Defaults to the image's default projection.
crsTransform: A comma-separated string of 6 numbers describing
the affine transform of the coordinate reference system of the
exported image's projection, in the order: xScale, xShearing,
xTranslation, yShearing, yScale and yTranslation. Defaults to
the image's native CRS transform.
maxPixels: The maximum allowed number of pixels in the exported
image. The task will fail if the exported region covers more
pixels in the specified projection. Defaults to 100,000,000.
shardSize: Size in pixels of the tiles in which this image will be
computed. Defaults to 256.
fileDimensions: The dimensions in pixels of each image file, if the
image is too large to fit in a single file. May specify a
single number to indicate a square shape, or a tuple of two
dimensions to indicate (width,height). Note that the image will
still be clipped to the overall image dimensions. Must be a
multiple of shardSize.
skipEmptyTiles: If true, skip writing empty (i.e. fully-masked)
image tiles. Defaults to false.
fileFormat: The string file format to which the image is exported.
Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to
'GeoTIFF'.
formatOptions: A dictionary of string keys to format specific options.
**kwargs: Holds other keyword arguments that may have been deprecated
such as 'crs_transform', 'driveFolder', and 'driveFileNamePrefix'.
"""
if not isinstance(ee_object, ee.ImageCollection):
raise ValueError("The ee_object must be an ee.ImageCollection.")
try:
count = int(ee_object.size().getInfo())
print(f"Total number of images: {count}\n")
if (descriptions is not None) and (len(descriptions) != count):
raise ValueError(
"The number of descriptions is not equal to the number of images."
)
if descriptions is None:
descriptions = ee_object.aggregate_array("system:index").getInfo()
images = ee_object.toList(count)
if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI.
return
for i in range(0, count):
image = ee.Image(images.get(i))
description = descriptions[i]
ee_export_image_to_drive(
image,
description,
folder,
fileNamePrefix,
dimensions,
region,
scale,
crs,
crsTransform,
maxPixels,
shardSize,
fileDimensions,
skipEmptyTiles,
fileFormat,
formatOptions,
**kwargs,
)
except Exception as e:
print(e)
def ee_export_image_collection_to_asset(
ee_object,
descriptions=None,
assetIds=None,
pyramidingPolicy=None,
dimensions=None,
region=None,
scale=None,
crs=None,
crsTransform=None,
maxPixels=None,
**kwargs,
):
"""Creates a batch task to export an ImageCollection as raster images to Google Drive.
Args:
ee_object: The image collection to export.
descriptions: A list of human-readable names of the tasks.
assetIds: The destination asset ID.
pyramidingPolicy: The pyramiding policy to apply to each band in the
image, a dictionary keyed by band name. Values must be
one of: "mean", "sample", "min", "max", or "mode".
Defaults to "mean". A special key, ".default", may be used to
change the default for all bands.
dimensions: The dimensions of the exported image. Takes either a
single positive integer as the maximum dimension or "WIDTHxHEIGHT"
where WIDTH and HEIGHT are each positive integers.
region: The lon,lat coordinates for a LinearRing or Polygon
specifying the region to export. Can be specified as a nested
lists of numbers or a serialized string. Defaults to the image's
region.
scale: The resolution in meters per pixel. Defaults to the
native resolution of the image assset unless a crsTransform
is specified.
crs: The coordinate reference system of the exported image's
projection. Defaults to the image's default projection.
crsTransform: A comma-separated string of 6 numbers describing
the affine transform of the coordinate reference system of the
exported image's projection, in the order: xScale, xShearing,
xTranslation, yShearing, yScale and yTranslation. Defaults to
the image's native CRS transform.
maxPixels: The maximum allowed number of pixels in the exported
image. The task will fail if the exported region covers more
pixels in the specified projection. Defaults to 100,000,000.
**kwargs: Holds other keyword arguments that may have been deprecated
such as 'crs_transform'.
"""
if not isinstance(ee_object, ee.ImageCollection):
raise ValueError("The ee_object must be an ee.ImageCollection.")
try:
count = int(ee_object.size().getInfo())
print(f"Total number of images: {count}\n")
if (descriptions is not None) and (len(descriptions) != count):
print("The number of descriptions is not equal to the number of images.")
return
if descriptions is None:
descriptions = ee_object.aggregate_array("system:index").getInfo()
if assetIds is None:
assetIds = descriptions
images = ee_object.toList(count)
if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI.
return
for i in range(0, count):
image = ee.Image(images.get(i))
description = descriptions[i]
assetId = assetIds[i]
ee_export_image_to_asset(
image,
description,
assetId,
pyramidingPolicy,
dimensions,
region,
scale,
crs,
crsTransform,
maxPixels,
**kwargs,
)
except Exception as e:
print(e)
def ee_export_image_collection_to_cloud_storage(
ee_object,
descriptions=None,
bucket=None,
fileNamePrefix=None,
dimensions=None,
region=None,
scale=None,
crs=None,
crsTransform=None,
maxPixels=None,
shardSize=None,
fileDimensions=None,
skipEmptyTiles=None,
fileFormat=None,
formatOptions=None,
**kwargs,
):
"""Creates a batch task to export an ImageCollection as raster images to Google Drive.
Args:
ee_object: The image collection to export.
descriptions: A list of human-readable names of the tasks.
bucket: The name of a Cloud Storage bucket for the export.
fileNamePrefix: Cloud Storage object name prefix for the export.
Defaults to the name of the task.
dimensions: The dimensions of the exported image. Takes either a
single positive integer as the maximum dimension or "WIDTHxHEIGHT"
where WIDTH and HEIGHT are each positive integers.
region: The lon,lat coordinates for a LinearRing or Polygon
specifying the region to export. Can be specified as a nested
lists of numbers or a serialized string. Defaults to the image's
region.
scale: The resolution in meters per pixel. Defaults to the
native resolution of the image assset unless a crsTransform
is specified.
crs: The coordinate reference system of the exported image's
projection. Defaults to the image's default projection.
crsTransform: A comma-separated string of 6 numbers describing
the affine transform of the coordinate reference system of the
exported image's projection, in the order: xScale, xShearing,
xTranslation, yShearing, yScale and yTranslation. Defaults to
the image's native CRS transform.
maxPixels: The maximum allowed number of pixels in the exported
image. The task will fail if the exported region covers more
pixels in the specified projection. Defaults to 100,000,000.
shardSize: Size in pixels of the tiles in which this image will be
computed. Defaults to 256.
fileDimensions: The dimensions in pixels of each image file, if the
image is too large to fit in a single file. May specify a
single number to indicate a square shape, or a tuple of two
dimensions to indicate (width,height). Note that the image will
still be clipped to the overall image dimensions. Must be a
multiple of shardSize.
skipEmptyTiles: If true, skip writing empty (i.e. fully-masked)
image tiles. Defaults to false.
fileFormat: The string file format to which the image is exported.
Currently only 'GeoTIFF' and 'TFRecord' are supported, defaults to
'GeoTIFF'.
formatOptions: A dictionary of string keys to format specific options.
**kwargs: Holds other keyword arguments that may have been deprecated
such as 'crs_transform'.
"""
if not isinstance(ee_object, ee.ImageCollection):
raise ValueError("The ee_object must be an ee.ImageCollection.")
try:
count = int(ee_object.size().getInfo())
print(f"Total number of images: {count}\n")
if (descriptions is not None) and (len(descriptions) != count):
print("The number of descriptions is not equal to the number of images.")
return
if descriptions is None:
descriptions = ee_object.aggregate_array("system:index").getInfo()
images = ee_object.toList(count)
if os.environ.get("USE_MKDOCS") is not None: # skip if running GitHub CI.
return
for i in range(0, count):
image = ee.Image(images.get(i))
description = descriptions[i]
ee_export_image_to_cloud_storage(
image,
description,
bucket,
fileNamePrefix,
dimensions,
region,
scale,
crs,
crsTransform,
maxPixels,
shardSize,
fileDimensions,
skipEmptyTiles,
fileFormat,
formatOptions,
**kwargs,
)
except Exception as e:
print(e)
def ee_export_geojson(
ee_object, filename=None, selectors=None, timeout=300, proxies=None
):
"""Exports Earth Engine FeatureCollection to geojson.
Args:
ee_object (object): ee.FeatureCollection to export.
filename (str): Output file name. Defaults to None.
selectors (list, optional): A list of attributes to export. Defaults to None.
timeout (int, optional): Timeout in seconds. Defaults to 300 seconds.
proxies (dict, optional): Proxy settings. Defaults to None.
"""
if not isinstance(ee_object, ee.FeatureCollection):
print("The ee_object must be an ee.FeatureCollection.")
return
if filename is None:
out_dir = os.path.join(os.path.expanduser("~"), "Downloads")
filename = os.path.join(out_dir, random_string(6) + ".geojson")
allowed_formats = ["geojson"]
filename = os.path.abspath(filename)
basename = os.path.basename(filename)
name = os.path.splitext(basename)[0]
filetype = os.path.splitext(basename)[1][1:].lower()
if not (filetype.lower() in allowed_formats):
print("The output file type must be geojson.")
return
if selectors is None:
selectors = ee_object.first().propertyNames().getInfo()
selectors = [".geo"] + selectors
elif not isinstance(selectors, list):
print("selectors must be a list, such as ['attribute1', 'attribute2']")
return
else:
allowed_attributes = ee_object.first().propertyNames().getInfo()
for attribute in selectors:
if not (attribute in allowed_attributes):
print(
"Attributes must be one chosen from: {} ".format(
", ".join(allowed_attributes)
)
)
return
try:
# print('Generating URL ...')
url = ee_object.getDownloadURL(
filetype=filetype, selectors=selectors, filename=name
)
# print('Downloading data from {}\nPlease wait ...'.format(url))
r = None
r = requests.get(url, stream=True, timeout=timeout, proxies=proxies)
if r.status_code != 200:
print("An error occurred while downloading. \n Retrying ...")
try:
new_ee_object = ee_object.map(filter_polygons)
print("Generating URL ...")
url = new_ee_object.getDownloadURL(
filetype=filetype, selectors=selectors, filename=name
)
print(f"Downloading data from {url}\nPlease wait ...")
r = requests.get(url, stream=True, timeout=timeout, proxies=proxies)
except Exception as e:
print(e)
with open(filename, "wb") as fd:
for chunk in r.iter_content(chunk_size=1024):
fd.write(chunk)
except Exception as e:
print("An error occurred while downloading.")
if r is not None:
print(r.json()["error"]["message"])
return
with open(filename) as f:
geojson = f.read()
return geojson
def ee_export_vector(
ee_object,
filename,
selectors=None,
verbose=True,
keep_zip=False,
timeout=300,
proxies=None,
):
"""Exports Earth Engine FeatureCollection to other formats, including shp, csv, json, kml, and kmz.
Args:
ee_object (object): ee.FeatureCollection to export.
filename (str): Output file name.
selectors (list, optional): A list of attributes to export. Defaults to None.
verbose (bool, optional): Whether to print out descriptive text.
keep_zip (bool, optional): Whether to keep the downloaded shapefile as a zip file.
timeout (int, optional): Timeout in seconds. Defaults to 300 seconds.
proxies (dict, optional): A dictionary of proxies to use. Defaults to None.
"""
if not isinstance(ee_object, ee.FeatureCollection):
raise ValueError("ee_object must be an ee.FeatureCollection")