 # 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
ee.Initialize()

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

# define the image
collection = ee.ImageCollection("COPERNICUS/S2").filterBounds(area)\
.filterDate("2018-01-01","2019-01-10")\
.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.reduceRegion(reducer=ee.Reducer.toList(),\
geometry=area,\
maxPixels=1e13,\
scale=10);

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 - uniqueLats
xs = uniqueLons - uniqueLons

# 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),1):
if lats[counter] == uniqueLats[y] and lons[counter] == uniqueLons[x] and counter &lt; len(lats)-1:
counter+=1
arr[len(uniqueLats)-1-y,x] = data[counter] # we start from lower left corner
return arr

# map over the image collection
myCollection  = collection.map(anyFunction)

# get the median
result = ee.Image(myCollection.median()).rename([&#039;result&#039;])

# 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
plt.imshow(image)
plt.show()

```

## One comment

1. Boud says:

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.