Google Earth Engine lets you export images, map tiles, tables and videos from Earth Engine. The exports can only be sent to your Google Drive account, to Google Cloud Storage or to a new Earth Engine asset. Satellite images are large in size so your free drive storage will fill up in no time and then you are a force to buy the storage which is not cheap if you are living in developing countries. But we can take advantage of the google python API to export the images, image collections directly to your local computer without uploading to your drive.
The Google Earth Engine (GEE) Python API facilitates interacting with Earth Engine servers using the Python programming language. It is available as a Python package that can be installed locally or within the cloud and accessed from a command-line interpreter or within a Jupyter notebook.
Step 1
The Python API package is called ee. It must also be initialized for every new session and script.
#If not already installed, uncomment the line below to install geemap
#!pip install geemap
import ilwis
import requests
from zipfile import ZipFile
from osgeo import gdal
import numpy as np
import os
import matplotlib.pyplot as plt
gdal connector: ilwis3 connector: Organizing data:
# import Google earth engine module
import ee
#Authenticate the Google earth engine with google account
#if not already authonticated, uncomment the line below
#ee.Authenticate()
ee.Initialize()
Step 2
Load the Image or ImageCollection you like. In this example, the selected image is loaded for download
geometry = ee.Geometry.Rectangle ([34.3705, -20.2326, 34.7852, -19.2839]) # Beira, Mozambique
bandlist = ['VV']
#load image
MyImage = ee.ImageCollection('COPERNICUS/S1_GRD').filterDate('2019-03-19', '2019-03-21').select(bandlist).filterBounds(geometry) \
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH'))
Step 3
Create a Python function to get the download link:
#create function to download the image or imagecollection as you desire
def downloader(ee_object,region):
#try:
#download image
if isinstance(ee_object, ee.image.Image):
print('Its Image')
url = ee_object.getDownloadUrl({
'scale': 30,
'crs': 'EPSG:4326',
'region': region
})
return url
#download imagecollection
elif isinstance(ee_object, ee.imagecollection.ImageCollection):
print('Its ImageCollection')
ee_object_new = ee_object.mosaic()
url = ee_object_new.getDownloadUrl({
'scale': 30,
'crs': 'EPSG:4326',
'region': region
})
return url
#except:
# print("Could not download")
def download(url, outputfile):
with requests.get(url, stream=True) as response:
response.raise_for_status()
total_length = response.headers.get('content-length')
if total_length is not None:
total_length = int(total_length)
downloaded_length = 0
with open(outputfile, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
downloaded_length += len(chunk)
f.write(chunk)
Step 4
Select the region or Area of Interest
work_dir = os.getcwd()+'/data'
print("current dir is: %s" % (os.getcwd()))
print("current working directory is:",work_dir)
if os.path.isdir(work_dir):
print("Folder exists")
else:
print("Folder doesn't exists")
os.mkdir(work_dir)
current dir is: /home/eoafrica/surface_flood current working directory is: /home/eoafrica/surface_flood/data Folder exists
region = geometry.toGeoJSONString() #region must in JSON format
url = downloader(MyImage,region) #call function
print(url) #print the download URL
filename = work_dir +'/download.zip'
download(url, filename)
Its ImageCollection https://earthengine.googleapis.com/v1/projects/earthengine-legacy/thumbnails/4fb78d418ee9ad9172e84d2f0c136b68-62808b2f71e12aaf680d3a6a49981c8e:getPixels
Final step:
Note the URL created, you can copy and paste it in any browser, the file will be downloaded. The code field below will automatically download the link created into the active notebook folder.
Note that Google has a limitation of 1 GB per download.
z = ZipFile(filename)
for file in z.namelist():
f = z.open(file)
mmap_name = '/vsimem/'+file
gdal.FileFromMemBuffer(mmap_name, f.read())
f.close()
dataset=gdal.Open(mmap_name)
file = file.replace('.tif','.mpr')
file = file.replace('download.','')
file = 'data/' + file #note folder location
gdal.Translate(file, dataset, format='ILWIS')
gdal.Unlink(mmap_name)
os.remove(file + '.aux.xml')
z.close()
os.remove(filename)
Once images are locally available create cross polarized image, called 'cross' (mapcalc formula: ratio:= VV/VH), stretch the three maps and create a maplist to display the data as a colour composite: vv_stretch=red, vh_stretch=green and cross_stretch=blue)
#to work with ILWIS first set the working directory, here the current folder is used
data_dir = os.getcwd() + '/' + 'data'
ilwis.setWorkingCatalog(data_dir)
print(data_dir)
/home/eoafrica/surface_flood/data gdal connector: ilwis3 connector: Organizing data:
rc1 = ilwis.RasterCoverage('VV.mpr')
rc2 = ilwis.RasterCoverage('VH.mpr')
#calculate the cross polarized image (vv/vh)
VC = ilwis.do('mapcalc','(@1/@2)', rc1, rc2)
VC = ilwis.do('setvaluerange', VC, -1000, 1000, 0.001)
VC.store('VC.mpr') #uncomment if you want to store the image on disk
mapcalc: in 0.829239 secondssetvaluerange: in 0.377228 seconds
You can also use the ILWIS 386 desktop software, create a maplist of VH, VV and VC and display the maplist as a colour composite, using red=VH, green=VV and blue=VC. Add 'openstreetmap' to the visualization, change the transparency and check the area affected by floods
#uncomment the lines below with the B?s.store command, to store the data to disk
rc1s = ilwis.do('linearstretch',rc1,1)
rc1s = ilwis.do('setvaluerange', rc1s, 0, 255, 1)
#rc1s.store('s1_VVs.mpr')
rc1_2np = np.fromiter(iter(rc1s), np.ubyte, rc1s.size().linearSize())
rc1_2np = rc1_2np.reshape((rc1s.size().ysize, rc1s.size().xsize))
rc2s = ilwis.do('linearstretch',rc2,1)
rc2s = ilwis.do('setvaluerange', rc2s, 0, 255, 1)
#rc2s.store('s1_VHs.mpr')
rc2_2np = np.fromiter(iter(rc2s), np.ubyte, rc2s.size().linearSize())
rc2_2np = rc2_2np.reshape((rc2s.size().ysize, rc2s.size().xsize))
rc3s = ilwis.do('linearstretch',VC,1)
rc3s = ilwis.do('setvaluerange', rc3s, 0, 255, 1)
#rc3s.store('s1_VCs.mpr')
rc3_2np = np.fromiter(iter(rc3s), np.ubyte, rc3s.size().linearSize())
rc3_2np = rc3_2np.reshape((rc3s.size().ysize, rc3s.size().xsize))
setvaluerange: in 0.418494 seconds
setvaluerange: in 0.447585 seconds
setvaluerange: in 0.492687 seconds
# create color composite (in RGB)
fc = np.dstack((rc2_2np, rc1_2np, rc3_2np))
#create a plot
fig1 = plt.figure(figsize=(15, 10))
plt.imshow(fc);
fig1.savefig(work_dir + '/s1_cc.png')