Skip to content

BagOfVisualWords: a visual vocabulary

BagOfVisualWords cuts a frame into patches, describes each patch by the directions of its edges, learns a vocabulary of words with an internal OnlineKMeans, and turns a frame into a histogram of words. Its code is in core/signals/vision; it is on this page because it is the k-means applied to images. The overview of the section is on Clustering.

A visual vocabulary of image patches

An image is cut into small patches; each patch is described by the directions of its edges; online k-means groups the patch descriptions into "visual words"; a frame becomes a histogram of the words it contains.

import numpy as np
from dense_armor.core.signals.vision.vocabulary import BagOfVisualWords

vert = np.zeros((32, 32), dtype=np.float32)
vert[:, ::4] = 1.0
horz = vert.T.copy()
bow = BagOfVisualWords(n_words=4, patch_size=8, n_bins=4)
for _ in range(10):
    bow.learn_one({"frame": vert})
    bow.learn_one({"frame": horz})
print(bow.transform_one({"frame": vert})["hist"], bow.transform_one({"frame": horz})["hist"])
[0.0, 0.25, 0.0, 0.75] [0.25, 0.0, 0.75, 0.0]

Vertical stripes and horizontal stripes use different words, so their histograms do not overlap: two textures, two signatures. The vocabulary is learned online with OnlineKMeans on the descriptors of the 8×8 patches, so the same estimator can be fed patches from any number of frames without ever storing them; a frame becomes a fixed-length histogram, a signature ready for a classifier.

The two frames, vertical stripes and horizontal stripes, and their histograms over the 4 visual words: the vertical stripes use the words 1 and 3 (0.25 and 0.75), the horizontal stripes the words 0 and 2 (0.25 and 0.75); no word is shared.

The picture shows the two frames and their histograms. The vertical stripes use the words 1 and 3 (0.25 and 0.75 of their patches), the horizontal stripes the words 0 and 2 (0.25 and 0.75): no word is shared, so the two signatures do not overlap.

The parameters

Parameter Meaning Default
n_words size of the visual vocabulary 8
patch_size side of a square patch in pixels 8
n_bins number of gradient orientation bins inside a patch 8
seed passed to the internal OnlineKMeans 0

A frame that is empty, has a wrong shape or contains a value that is not finite is skipped and counted in n_missing.

API reference

vocabulary

Bag of visual words: a k-means vocabulary over image patches.

The frame is split into square patches (default 8 by 8 pixels). Each patch is described with a small histogram of oriented gradients (Huang and Huang 2017), the same construction used by the frame features. An online k-means learns a vocabulary of n_words visual words over the patch descriptors, one word per cluster. A frame becomes a normalised histogram of visual words: every patch votes for its nearest word and the histogram is divided by the number of patches. The result is a fixed-length signature of the frame, the missing piece of the visual pipeline.

The vocabulary is grown online, so the same estimator can be fed patch descriptors from many frames without ever storing them.

Examples:

>>> import numpy as np
>>> from dense_armor.core.signals.vision.vocabulary import BagOfVisualWords
>>> bow = BagOfVisualWords(n_words=3, patch_size=8, n_bins=4)
>>> img = np.zeros((16, 16), dtype=np.float32)
>>> img[:, 8:] = 1.0
>>> out = bow.transform_one({"frame": img})
>>> len(out["hist"])
3
References

Huang, C., Huang, J. (2017). A fast HOG descriptor using lookup table and integral image. arXiv:1703.06256.

BagOfVisualWords

BagOfVisualWords(
    n_words: int = 8,
    patch_size: int = 8,
    n_bins: int = 8,
    seed: int = 0,
)

Bases: Transformer

Visual vocabulary over image patches and per-frame histogram.

learn_one extracts patches from a frame and feeds their descriptors to an internal :class:OnlineKMeans. transform_one returns a normalised histogram of word counts. A frame that is empty, has a wrong shape, or contains a non-finite value is skipped and counted in n_missing.

Memory grows with the vocabulary (n_words centres of 2 * n_bins floats each) and the number of patches per frame, both bounded, so the footprint is fixed.

Parameters:

Name Type Description Default
n_words int

size of the visual vocabulary.

8
patch_size int

side of a square patch in pixels.

8
n_bins int

number of gradient orientation bins inside a patch.

8
seed int

passed to the internal :class:OnlineKMeans.

0

Raises:

Type Description
ValueError

if any parameter is not positive.

Source code in dense_armor/core/signals/vision/vocabulary.py
def __init__(
    self,
    n_words: int = 8,
    patch_size: int = 8,
    n_bins: int = 8,
    seed: int = 0,
) -> None:
    if n_words < 1:
        raise ValueError(f"n_words must be >= 1, got {n_words}")
    if patch_size < 2:
        raise ValueError(f"patch_size must be >= 2, got {patch_size}")
    if n_bins < 1:
        raise ValueError(f"n_bins must be >= 1, got {n_bins}")
    self.n_words = n_words
    self.patch_size = patch_size
    self.n_bins = n_bins
    self.seed = seed
    self.kmeans_ = OnlineKMeans(k=n_words, seed=seed)
    self.n_missing_ = 0

learn_one

learn_one(
    x: Any, y: Any = None, t: float | None = None
) -> BagOfVisualWords

Update the vocabulary with the patches of one frame.

Source code in dense_armor/core/signals/vision/vocabulary.py
def learn_one(
    self, x: Any, y: Any = None, t: float | None = None
) -> "BagOfVisualWords":
    """Update the vocabulary with the patches of one frame."""
    self._time_step(t)
    img = _as_array(x)
    if img is None:
        self.n_missing_ += 1
        return self
    descs = self._descriptors(img)
    if descs.shape[0] == 0:
        self.n_missing_ += 1
        return self
    for d in descs:
        self.kmeans_.learn_one({"_d": d.tolist()})
    return self

transform_one

transform_one(x: Any, t: float | None = None) -> dict

Return {"hist": [...]}, the normalised word histogram.

Source code in dense_armor/core/signals/vision/vocabulary.py
def transform_one(self, x: Any, t: float | None = None) -> dict:
    """Return ``{"hist": [...]}``, the normalised word histogram."""
    img = _as_array(x)
    if img is None:
        self.n_missing_ += 1
        return {"hist": [0.0] * self.n_words}
    descs = self._descriptors(img)
    if descs.shape[0] == 0 or self.kmeans_.centers_ is None:
        return {"hist": [0.0] * self.n_words}
    hist = np.zeros(self.n_words, dtype=get_default_dtype())
    for d in descs:
        j = self.kmeans_.predict_one({"_d": d.tolist()})
        hist[j] += 1.0
    s = hist.sum()
    if s > 0:
        hist = hist / s
    return {"hist": hist.tolist()}

Details

  • Sources: Huang, C., Huang, J. (2017), "A fast HOG descriptor using lookup table and integral image", arXiv:1703.06256.