# 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#show-individual-pca-component-images # region: setup import os from pathlib import Path import joblib import matplotlib.pyplot as plt 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") 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 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 reflectance = open_reflectance_cube() pca = load_pca_model() 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) fig, axes = plt.subplots(3, 2, figsize=(10, 12)) axes = axes.ravel() for component_index, ax in enumerate(axes): component = pca_preview[:, :, component_index] im = ax.imshow(component, cmap="gray") ax.set_title(f"PC{component_index + 1}") ax.axis("off") fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) plt.tight_layout() plt.show() # end region