Custom operations#
The HV SDK provides facilities for running custom Python code inside its pipeline system. This means that you can take advantage of the same lazy calculations and efficient streaming, that the built-in operations use.
In order to ease the use of these custom operations, the SDK provides a number of helper functions.
At the simplest level, a custom operation can be created by using the hsi.HSImage.ufunc()
method
like so:
def my_function(plane: np.ndarray) -> np.ndarray:
return plane.mean(axis=1, keepdims=True)
# Apply `my_function` to each plane of the image.
res = img.ufunc(my_function)
# The resulting image uses the same lazy pipeline as the built-in operations.
res.plane_axis(200, hsi.bands)
# When resolving the entire image, the function is applied on a plane-by-plane basis.
out = res.to_numpy()
This method does not account for different interleaves and always operates on the inner two dimensions of the image.
General operations#
The SDK provides a decorator hsi.util.operation()
, that ensures a desired interleave and
wraps a function so it can be used directly with hsi.HSImage
:
from hsi.util import operation
@operation(hsi.bip)
def my_function(plane: np.ndarray) -> np.ndarray:
return plane.mean(axis=1, keepdims=True)
# The call now ensures that the interleave is consistent.
res = my_function(img)
Machine learning models#
The SDK also provides a helper function hsi.util.predictor()
for adapting certain scikit-learn like ML models to hsi.HSImage
s.
It support models that use individual spatial pixels as input.
from hsi.util import predictor
from sklearn.linear_model import LinearRegression
img = hsi.open(<path>)
model = LinearRegression()
model.fit(...) # Training step
hsimage_predictor = predictor(model)
res = hsimage_predictor(img)
# Again, the operation is lazy and is only applied when necessary.
out = res.to_numpy()
# This means that operations like slicing will reduce the number of computations.
out_small = res[50:60, :, :].to_numpy()