# This file was extracted from the HV SDK Docusaurus examples. # It is intended as a downloadable, runnable companion to the documentation. # Set HSI_EXAMPLE_BASE_DIR and related env vars to use your own data. # Source page: /hsi/hv_sdk/examples/pca#fit-pca-and-preview-components # region: setup import os from pathlib import Path import numpy as np import qtec_hv_sdk as hs from qtec_hv_sdk.preprocessing import make_reference from qtec_hv_sdk.preprocessing import reflectance_calibration BASE_DIR = Path(os.environ.get("HSI_EXAMPLE_BASE_DIR", "/path/to/HSI_data/nuts")) if not BASE_DIR.exists(): raise SystemExit( "Run: 'export HSI_EXAMPLE_BASE_DIR=/path/to/HSI_data/' to setup the " "folder containing the example datacubes." ) TRAIN_CUBE = os.environ.get("HSI_EXAMPLE_TRAIN_CUBE", "mix1.pam") DARK_REF = os.environ.get("HSI_EXAMPLE_DARK_REF", "dark_ref.pam") WHITE_REF = os.environ.get("HSI_EXAMPLE_WHITE_REF", "white_ref.pam") PCA_MODEL_PATH = Path(os.environ.get("HSI_EXAMPLE_PCA_MODEL", "pca_model.joblib")) def make_references(): dark = hs.open(str(BASE_DIR / DARK_REF)) white = hs.open(str(BASE_DIR / WHITE_REF)) return make_reference(dark), make_reference(white) def open_reflectance_cube(cube_name=TRAIN_CUBE): dark_ref, white_ref = make_references() img = hs.open(str(BASE_DIR / cube_name)) return reflectance_calibration(img, white_ref, dark_ref, clip=True) def contrast_stretch(image, percentiles=(1, 99)): low, high = np.percentile(image, percentiles) return np.clip((image - low) / (high - low + 1e-8), 0, 1) # end region # region: example import joblib import matplotlib.pyplot as plt from qtec_hv_sdk.ml import pca_helper from sklearn.decomposition import PCA reflectance = open_reflectance_cube() line_step = 50 sample_step = 20 n_components = 6 sample_stop = (reflectance.shape.samples // sample_step) * sample_step sample_cube = reflectance[0:200:line_step, 0:sample_stop:sample_step, :].to_numpy_with_interleave(hs.bip) sample_pixels = sample_cube.reshape(-1, sample_cube.shape[-1]) pca = PCA(n_components=n_components, random_state=42) pca.fit(sample_pixels) print(f"Explained variance: {pca.explained_variance_ratio_}") print(f"Total explained variance: {pca.explained_variance_ratio_.sum():.3f}") # Save the PCA model joblib.dump(pca, PCA_MODEL_PATH) print(f"Saved PCA model to {PCA_MODEL_PATH}") hs_pca = pca_helper(pca) preview_source = reflectance[0:250, 0:400, :] pca_image = hs_pca(preview_source) pca_preview = pca_image.to_numpy_with_interleave(hs.bip) rgb_preview = pca_preview[:, :, :3].copy() for channel in range(3): rgb_preview[:, :, channel] = contrast_stretch(rgb_preview[:, :, channel]) plt.imshow(rgb_preview) plt.title("PCA RGB preview: PC1, PC2, PC3") plt.axis("off") plt.show() # end region