# 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#apply-it-to-another-cube # region: setup import os from pathlib import Path import joblib import matplotlib.pyplot as plt import numpy as np import qtec_hv_sdk as hs from qtec_hv_sdk.ml import pca_helper 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") TEST_CUBE = os.environ.get("HSI_EXAMPLE_TEST_CUBE", "mix2.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) def load_pca_model(): if not PCA_MODEL_PATH.exists(): raise SystemExit( f"PCA model not found at {PCA_MODEL_PATH}. " "Run 01_principal_component_analysis.py first, or set HSI_EXAMPLE_PCA_MODEL." ) return joblib.load(PCA_MODEL_PATH) # end region # region: example pca = load_pca_model() test_reflectance = open_reflectance_cube(TEST_CUBE) hs_pca = pca_helper(pca) test_crop = test_reflectance[0:250, 0:400, :] test_pca = hs_pca(test_crop) test_preview = test_pca.to_numpy_with_interleave(hs.bip) rgb_preview = test_preview[:, :, :3].copy() for channel in range(3): rgb_preview[:, :, channel] = contrast_stretch(rgb_preview[:, :, channel]) plt.imshow(rgb_preview) plt.title("Test cube projected with saved PCA") plt.axis("off") plt.show() # end region