Google Earth Engine to Numpy

Export the the result of your earth engine calculation to an numpy array


The code below imports sentinel-2 satellite imagery.
use the first function do any calculation on the image collection. The second function will get the latitude, longitude and value of each pixel. The third function will convert the 1 dimensional array into a 2 dimensional image.

import ee
import numpy as np
from osgeo import gdal
from osgeo import osr
import time

# init the ee object

# Define the roi
area = ee.Geometry.Polygon([[105.4084512289977,12.960956032145036],\

# define the image
collection = ee.ImageCollection("COPERNICUS/S2").filterBounds(area)\
									  .select(['B8', 'B4'])

print(" number of image: ",collection.size().getInfo())

# perform any calculation on the image collection here
def anyFunction(img):
	ndvi = ee.Image(img.normalizedDifference(['B8', 'B4'])).rename(["ndvi"])
	return ndvi

# export the latitude, longitude and array
def LatLonImg(img):
	img = img.addBands(ee.Image.pixelLonLat())

	img = img.reduceRegion(reducer=ee.Reducer.toList(),\

 	data = np.array((ee.Array(img.get("result")).getInfo()))
	lats = np.array((ee.Array(img.get("latitude")).getInfo()))
	lons = np.array((ee.Array(img.get("longitude")).getInfo()))
	return lats, lons, data

# covert the lat, lon and array into an image
def toImage(lats,lons,data):

	# get the unique coordinates
	uniqueLats = np.unique(lats)
	uniqueLons = np.unique(lons)

	# get number of columns and rows from coordinates
	ncols = len(uniqueLons)
	nrows = len(uniqueLats)

	# determine pixelsizes
	ys = uniqueLats[1] - uniqueLats[0]
	xs = uniqueLons[1] - uniqueLons[0]

	# create an array with dimensions of image
	arr = np.zeros([nrows, ncols], np.float32) #-9999

	# fill the array with values
	counter =0
	for y in range(0,len(arr),1):
		for x in range(0,len(arr[0]),1):
			if lats[counter] == uniqueLats[y] and lons[counter] == uniqueLons[x] and counter < len(lats)-1:
				arr[len(uniqueLats)-1-y,x] = data[counter] # we start from lower left corner
	return arr

# map over the image collection
myCollection  =

# get the median
result = ee.Image(myCollection.median()).rename(['result'])

# get the lon, lat and result as 1d array
lat, lon, data = LatLonImg(result)

# 1d to 2d array
image  = toImage(lat,lon,data)

# in case you want to plot the image
import matplotlib.pyplot as plt

One comment

  1. Thanks for this new version of your GEE to Numpy script. I am running it to convert a Sentinel 2 based NDVI image to numpy. Unfortunately the length of data is less than of lat and lon. The study area is clipped from the S2 image at the start of the script using a shape file.

Leave a Reply