2

I would like to do a PCA on a 9band raster image to reduce the total number of inputs bands to 3. However, I'm not able to do it as I don't think I understand what sklearn is doing in its PCA.

Some code:

import skimage, rasterio, numpy, os
from rasterio.plot import reshape_as_raster, reshape_as_image

infile = r"C:/.../.../Sentinelimage9bands.tif"
im = rasterio.open(infile)
arr = im.read()
pca = sklearn.decomposition.pca(n_components = 3)
arrs = reshape_as_image(arr)
pca.fit(arrs)

Resulting error: "Found array with dim 3. Estimator expected <= 2"

How am I supposed to do the PCA if it can't accept more than 2 dimensions? Moreover, if I flatten the array into 1 dimension, how will I know the explained variance from each band?

1

In your question, arr is likely a numpy array with size (9, ny, nx) (where ny and nx are the size of the image in pixels across). Most sklearn functions take a 2D array (often called X), with features (in your case, bands) as columns and samples (or pixels) as rows. So you'd have to reshape arr to be (9, nx*ny). Then it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.