This is how I get the PCs at the specified scale and in the specified region:
# Get the Principal Components (PCs)
pcImage = getPrincipalComponents(centered, scale, region) #this return PCA image
# Plot each PC as a new layer
for i in range(bandNames.length().getInfo()):
band = pcImage.bandNames().get(i)
map.addLayer(pcImage.select(['band']),{'min':-2,'max':2},'band')
Here is the pca functionin which am passing an ee image:
# Principal Components (PC) in the region as a new image.
def getPrincipalComponents(centered, scale, region):
#Collapse the bands of the image into a 1D array per pixel
arrays = centered.toArray()
#Compute the covariance of the bands within the region.
covar=arrays.reduceRegion(
reducer=ee.Reducer.centeredCovariance(),
geometry=region,
scale=scale,
maxPixels=1e9)
#Get the 'array' covariance result and cast to an array.
# This represents the band-to-band covariance within the region.
covarArray = ee.Array(covar.get('array'))
#Perform an eigen analysis and slice apart the values and vectors.
eigens = covarArray.eigen()
# This is a P-length vector of Eigenvalues.
eigenValues = eigens.slice(1, 0, 1)
# This is a PxP matrix with eigenvectors in rows.
eigenVectors = eigens.slice(1, 1)
# Convert the array image to 2D arrays for matrix computations.
arrayImage = arrays.toArray(1)
#Left multiply the image array by the matrix of eigenvectors.
principalComponents = ee.Image(eigenVectors).matrixMultiply(arrayImage)
# Turn the square roots of the Eigenvalues into a P-band image.
sdImage = ee.Image(eigenValues.sqrt())\
.arrayProject([0]).arrayFlatten([getNewBandNames('sd')])
# Turn the PCs into a P-band image, normalized by SD.
# Throw out an an unneeded dimension, [[]] -> [].
# Make the one band array image a multi-band image, [] -> image.
# Normalize the PCs by their SDs.
return principalComponents\
.arrayProject([0])\
.arrayFlatten([getNewBandNames('pc')])\
.divide(sdImage)
getPrincipalComponents not definde
when I try to run it. Try to share a MWE. – s.k Apr 18 '20 at 6:28centered
,region
andscale
. One of them probably is long, but expected a string. Check usingprint(type(centered), type(scale), type(region))
– Kadir Şahbaz Apr 19 '20 at 10:42