Recipes#
This section provides a few examples of how to implement common HSI processing operations using the library.
Spectral calibration#
1import hsi
2import numpy as np
3
4img = hsi.open("path/to/file.hdr").as_dtype(hsi.float32)
5
6# The white reference is included in the main image.
7white = img[:100, :, :]
8
9dark = hsi.open("path/to/dark.hdr").as_dtype(hsi.float32)
10
11# A reference image is taken as the mean of many individual images
12# to account for noise and local differences in the reference material.
13def mean_image(img):
14 return (
15 img
16 .mean_axis(hsi.lines)
17 .resolve() # Calculate the result and store it in memory.
18 )
19
20white_ref = mean_image(white)
21dark_ref = mean_image(dark)
22
23diff = white_ref - dark_ref
24
25calibrated = (img - dark_ref) / diff
Scatter correction (SNV)#
1import hsi
2import numpy as np
3
4# We assume this file is already calibrated (i.e. it contains reflectance values)
5img = hsi.open("path/to/file.hdr")
6
7mean = img.mean_axis(hsi.bands)
8std = img.std_axis(hsi.bands)
9
10snv = (img - mean) / std
Mean spectrum#
1import hsi
2import numpy as np
3
4img = hsi.open("path/to/file.hdr").as_dtype(hsi.float32)
5
6mean_spectrum = (
7 img[100:200, 100:200, :]
8 .mean_axis(hsi.bands)
9 .mean_axis(hsi.lines)
10 .to_numpy()
11 .flatten()
12)
PCA from random sample#
1import hsi
2import numpy as np
3from sklearn.decomposition import PCA
4
5img = hsi.open("path/to/file.hdr").as_dtype(hsi.float32)
6
7def gen_select(img, n_samples_per_line=10):
8 """Sample randomly (with the same number of samples per line) from the image."""
9
10 # Assumes BIL (doesn't work for BSQ/BIP)
11 def select(plane):
12 sample = np.random.choice(np.arange(plane.shape[1]), size=n_samples_per_line)
13 sample = plane[:, sample]
14 return sample
15
16 return img.ufunc(select) # Any Python function can be passed here
17
18# Get subsample from image in memory-efficient manner
19s_out = gen_select(img).to_numpy()
20s_out = s_out.transpose((0, 2, 1))
21s_out = s_out.reshape((-1, s_out.shape[2]))
22
23# Fit model
24model = PCA(n_components)
25model.fit(s_out)
26
27# Create transformation (you would likely want to resolve this)
28o = img.dot(model.components_.T, hsi.bands)