Skip to content

Instantly share code, notes, and snippets.

@jqtrde
Forked from celoyd/pca_multiband.py
Created December 17, 2015 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqtrde/67531d39f8790069da45 to your computer and use it in GitHub Desktop.
Save jqtrde/67531d39f8790069da45 to your computer and use it in GitHub Desktop.
# hackety hack
from sys import argv
import rasterio as rio
import numpy as np
from sklearn import decomposition
with rio.open(argv[1]) as src:
count = src.meta['count']
dtype = src.meta['dtype']
bidxs = [x+1 for x in range(count)]
# imagine this but faster and clearer:
pixels = (src.read(b) for b in bidxs)
pixels = np.dstack([c.ravel() for c in pixels])[0]
pca = decomposition.PCA(n_components=count, whiten=True)
pca.fit(pixels)
print pca.components_
out = pca.transform(pixels)
print count, range(count)
print out.shape
print pixels[0].shape
xyz = np.array([
out[:,c].reshape(src.meta['height'], src.meta['width'])
for c in range(count)
])
# scale up to fill out the bit depth:
xyz = np.array([
((c - np.amin(c))/(np.amax(c) - np.amin(c)))*np.iinfo(dtype).max
for c in xyz
])
xyz = xyz.astype(dtype)
with rio.open(argv[2],
'w',
driver='GTiff',
width=src.meta['width'],
height=src.meta['height'],
count=count,
dtype=dtype,
meta=src.meta,
photometric='rgb') as dst:
for bidx in bidxs:
dst.write_band(bidx, xyz[bidx-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment