Lambda

Lambda wraps any user-defined function as a feature extractor, so you can plug a custom descriptor into the embedders without writing a new FeatureExtractorBase subclass.

Usage

from pyvisim.features import Lambda

extractor = Lambda(func=my_descriptor_fn, output_dim=64)
  • func must take a single image (NumPy array), and return a (N, output_dim) array of descriptors.

  • output_dim is supplied explicitly because, unlike SIFT or a CNN layer, an arbitrary function has no inspectable descriptor size.

API reference

class pyvisim.features.Lambda(func, output_dim)[source]

Bases: FeatureExtractorBase

Lambda feature extractor that allows passing any user-defined function to extract features from images.

The function must accept a single argument (image as NumPy array), and output fixed-size feature vectors from each image.

Parameters:
__call__(image, /, *, dims='HWC', value_range=(0.0, 255.0))[source]

Extracts features from an image.

Parameters:
  • image (_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) – Input image as MatLike (NumPy array, torch tensor or array-like). It is normalized to a canonical uint8 (H, W, C) image before extraction.

  • dims (str) – Axis-label string, one character per array axis in order: "H" = height (rows), "W" = width (columns), "C" = channels. For example, "HWC" is height × width × channels (NumPy/OpenCV layout); "CHW" is channels × height × width (PyTorch layout). See pyvisim.typing.

  • value_range (tuple[float, float]) – The (low, high) range the input values live in; converted into the canonical [0, 255] range.

Returns:

Feature descriptors (NumPy array).

Return type:

ndarray[tuple[int, …], dtype[float32]]

extract_batch(images, /, *, dims='HWC', value_range=(0.0, 255.0))

Extracts features from a batch of images.

Returns one (N_i, D) feature array per image, in input order, since the number of descriptors an image yields varies from image to image. This default implementation extracts one image at a time; extractors that can do the whole batch in one go (e.g. a single forward pass through a neural network) override it.

Parameters:
  • images (Sequence[_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]]) – Batch of images, each a MatLike (NumPy array, torch tensor or array-like) normalized to a canonical uint8 (H, W, C) image before extraction.

  • dims (str) – Axis-label string, one character per array axis in order: "H" = height (rows), "W" = width (columns), "C" = channels. It applies to every image of the batch. See pyvisim.typing.

  • value_range (tuple[float, float]) – The (low, high) range the input values live in; converted into the canonical [0, 255] range.

Returns:

One (N_i, D) feature array per input image.

Return type:

list[ndarray[tuple[int, …], dtype[float32]]]

classmethod from_dict(state, **kwargs)

Rebuilds an object from a state dictionary (see to_dict() to see the expected format).

Parameters:
  • state (dict[str, Any]) – A JSON-safe description of the object.

  • kwargs (Any) – Objects the state cannot describe, forwarded by load_from_disk(). Implementations that accept none raise an error if kwargs is not empty.

Returns:

A ready-to-use instance.

Return type:

FeatureExtractorBase

classmethod load_from_disk(path, **kwargs)

Loads an object previously saved with save_to_disk().

Not every part of an object survives serialization: an arbitrary callable such as a torchvision transform has no portable description, so it is left out of the file. Pass such an object back here as a keyword argument.

Parameters:
  • path (str | Path) – Path to the file to load.

  • kwargs (Any) – Objects the file cannot hold, forwarded to from_dict().

Returns:

A ready-to-use instance.

Raises:
  • FileNotFoundError – If path does not exist.

  • ValueError – If the file is not a valid file of this kind or was saved by a different class.

  • TypeError – If the class does not take one of kwargs.

Return type:

_SerializableT

save_to_disk(path)

Saves the serialized state of this object to a file.

Parameters:

path (str | Path) – Target file path. Overwritten if it exists.

Returns:

The path of the written file.

Raises:

OSError – If the destination directory does not exist.

Return type:

Path

to_dict()

Serializes this object into a JSON-safe state dictionary.

The mapping holds the output of _state() plus the format version under "format_version" and the class name under "__class__". Arrays may be embedded as __ndarray__ nodes, which the serialization layer stores as binary tensors.

Returns:

A JSON-safe description suitable for from_dict().

Return type:

dict[str, Any]

property output_dim: int

The dimensionality (D) of each feature vector, i.e., shape[1] of the output.