TGraphX › Insights › Building Vision Graphs: Scene, Patch and kNN Recipes in TGraphX
← Back to Insights

Building Vision Graphs: Scene, Patch and kNN Recipes in TGraphX

Topic: Vision, multimodal and domain applications

Computer vision and graph learning have largely developed as separate research tracks. Vision models (CNNs, ViTs) process grid-structured data; GNNs process relationship-structured data. Tensor-valued graph learning connects the two: graph nodes carry image-like or volumetric features, and message passing moves information between nodes while each node keeps its spatial layout.

This article collects construction recipes for vision graphs and shows how to build and run them with TGraphX. These are candidate use cases, not evidence that a graph model beats a CNN or a transformer on them; this page measures no accuracy. Examples tested with TGraphX 1.5.1 on CPU with random data; the blocks build on each other, so run them in order.


Where Vision and Graphs Combine

Scene understanding. A scene graph represents a visual scene with one node per detected object and edges for spatial or semantic relationships between objects. Node features can be object crops of a feature map, [C, H, W]; message passing propagates context between related objects.

Medical image analysis. In brain connectivity studies, brain regions are nodes and functional or structural connectivity defines the edges. A region can carry a spatial map as its node feature. In pathology, tissue regions can be nodes connected by spatial proximity, each with a patch-level feature map.

Point cloud processing. A 3D point cloud becomes a graph by connecting each point to its nearest neighbours. Point features are usually vectors; tensor features only make sense if each point carries a local grid or patch.

Image segmentation. A superpixel graph has one node per superpixel. Node features can be a resized pixel crop [C, H, W] or aggregated statistics.

Video graphs. A video can be a graph with one node per frame (or per detected object) and edges between temporally adjacent or visually similar frames. If you first need detections, captions, or transcripts for a video as structured JSON, the AI-Powered Video Analyzer produces them on your own machine (captions and transcripts need its optional full install); it is a separate analysis tool and does not build graphs.

A video graph only holds what was sampled. How AI analyzes an entire video shows how sampling intervals and timestamps limit what per-frame records can say.


Recipe 1: A Scene Graph from Detected Boxes

Start from a backbone feature map and the boxes of a detector (both random or hand-written here). Crop every object to the same size with ROI align, connect each object to its nearest objects, and describe each edge by the relative position and size of the two boxes:

python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops import roi_align
import tgraphx as tgx
from tgraphx import Graph, GraphBatch, TensorGINLayer

torch.manual_seed(0)
feature_map = torch.randn(1, 16, 60, 80)          # [1, C, Hf, Wf] from a backbone
boxes = torch.tensor([                            # (x1, y1, x2, y2) on the feature map
    [ 2.,  3., 20., 25.], [15.,  5., 34., 30.], [40.,  8., 58., 40.], [52., 10., 78., 38.],
    [ 5., 32., 25., 55.], [22., 30., 45., 58.], [48., 36., 66., 59.], [64., 34., 79., 56.],
])

# Nodes: one fixed-size crop per object, [8, 16, 8, 8]
object_maps = roi_align(feature_map, [boxes], output_size=(8, 8), aligned=True)

# Edges: each object receives messages from its 3 nearest objects (box centres)
centers = (boxes[:, :2] + boxes[:, 2:]) / 2
sizes = boxes[:, 2:] - boxes[:, :2]
edge_index = tgx.build_knn_graph(centers, k=3, directed=True, self_loops=False).flip(0)

# Edge features [E, 4]: offset of the source box and log size ratio
src, dst = edge_index
edge_rel = torch.cat([(centers[src] - centers[dst]) / sizes[dst],
                      torch.log(sizes[src] / sizes[dst])], dim=1)

scene = Graph(node_features=object_maps, edge_index=edge_index, edge_features=edge_rel)

gin = TensorGINLayer(in_channels=16, out_channels=32, train_eps=True,
                     use_edge_features=True, edge_dim=4,
                     edge_features_kind="vector")         # [E, 4] -> per-channel bias
out = gin(scene.node_features, scene.edge_index, edge_features=scene.edge_features)
print(out.shape)                                          # torch.Size([8, 32, 8, 8])
assert (torch.bincount(scene.edge_index[1], minlength=8) == 3).all()

Messages travel from edge_index[0] to edge_index[1]. build_knn_graph with directed=True puts the query node in row 0, which is why the rows are flipped.

If relations should depend on overlap instead of distance, tgx.build_iou_graph(boxes, threshold=0.1, self_loops=False) connects boxes whose intersection-over-union reaches the threshold. A box that overlaps nothing then has no neighbours; TensorGINLayer still keeps its own features through the self term.


Recipe 2: A Patch Graph from One Image

tgx.image_to_patch_graph cuts an image into non-overlapping patches and connects horizontal and vertical neighbours, with self-loops. It returns a tuple, not a Graph:

python
image = torch.randn(3, 32, 32)                    # [C, H, W]

patches, patch_edges = tgx.image_to_patch_graph(image, patch_size=8)
print(patches.shape)                              # torch.Size([16, 3, 8, 8])
print(patch_edges.shape)                          # torch.Size([2, 64]): 48 neighbour + 16 self

patch_graph = Graph(node_features=patches, edge_index=patch_edges)

Patch order, overlapping patches, position information and memory cost are covered in when image patches become nodes. Trained versions on real data are in the MNIST as graph tutorial and the CIFAR image patch graph tutorial.


Recipe 3: A kNN Graph from Embeddings

When nodes already have embeddings (superpixels, frames, retrieved images), connect them by similarity:

python
embeddings = torch.randn(100, 512)

knn_edges = tgx.knn_graph(embeddings, k=5, metric="cosine", make_symmetric=True)
print(knn_edges.shape)                            # [2, E] with 500 <= E <= 1000
assert 500 <= knn_edges.shape[1] <= 1000
assert not (knn_edges[0] == knn_edges[1]).any()   # no self-loops

Each node picks 5 neighbours; adding the reverse edges and removing duplicates leaves between 500 and 1000 directed edges, depending on how many choices are mutual. With make_symmetric=False, each edge points from a node to its chosen neighbour, so flip the rows if nodes should aggregate from their own neighbours.


A Multi-Layer Model for Batches of Vision Graphs

This model keeps the spatial dimensions through three message-passing layers, pools the nodes of each graph with global_mean_pool, and classifies each graph:

python
from tgraphx import TensorGraphSAGELayer, global_mean_pool

class VisionGNN(nn.Module):
    def __init__(self, in_channels, height, width, num_classes):
        super().__init__()
        self.gin1 = TensorGINLayer(in_channels, 32, use_batchnorm=True)
        self.gin2 = TensorGINLayer(32, 64, use_batchnorm=True)
        self.sage = TensorGraphSAGELayer(64, 128, aggr="mean", normalize=True)
        self.classifier = nn.Linear(128 * height * width, num_classes)

    def forward(self, x, edge_index, batch):
        x = F.relu(self.gin1(x, edge_index))
        x = F.relu(self.gin2(x, edge_index))
        x = self.sage(x, edge_index)
        x = global_mean_pool(x, batch)            # [num_graphs, 128, H, W]
        return self.classifier(x.flatten(1))

graphs = [Graph(node_features=torch.randn(n, 16, 8, 8),
                edge_index=torch.randint(0, n, (2, 4 * n))) for n in (20, 12)]
vision_batch = GraphBatch(graphs)

model = VisionGNN(in_channels=16, height=8, width=8, num_classes=10)
logits = model(vision_batch.node_features, vision_batch.edge_index, vision_batch.batch)
print(logits.shape)                               # torch.Size([2, 10])

Without the batch vector, a mean over dim=0 would mix the nodes of all graphs. Note also that use_batchnorm=True computes statistics over every node in the batch during training, so one graph's output then depends on the others.


Multimodal Knowledge Graphs with Vision Entities

TGraphX's KG module supports entity features for multimodal knowledge graphs where some entities are represented by images (a full pipeline is in knowledge graph with vision and text entities). Each modality is stored as a tensor with one row per entity, plus a boolean mask saying which rows are real. MultimodalKGModel has one projector per modality and scores triples with a DistMult decoder:

python
from tgraphx.kg import (KnowledgeGraph, MultimodalKGModel,
                        ImageEntityProjector, VectorEntityProjector)

num_entities, num_relations = 100, 5
triples = torch.stack([torch.randint(0, num_entities, (200,)),      # head
                       torch.randint(0, num_relations, (200,)),     # relation
                       torch.randint(0, num_entities, (200,))], 1)  # tail
# KnowledgeGraph does not range-check triple ids, so check them here
assert triples[:, [0, 2]].max() < num_entities and triples[:, 1].max() < num_relations

is_image = torch.arange(num_entities) < 50        # entities 0-49 have images, 50-99 text
images = torch.zeros(num_entities, 3, 64, 64)
images[is_image] = torch.rand(50, 3, 64, 64)
text = torch.zeros(num_entities, 768)             # precomputed text embeddings
text[~is_image] = torch.randn(50, 768)

kg = KnowledgeGraph(triples, num_entities=num_entities, num_relations=num_relations,
                    entity_features={"image": images, "text": text},
                    entity_feature_masks={"image": is_image, "text": ~is_image})

kg_model = MultimodalKGModel(
    num_entities, num_relations, out_dim=32,
    projectors={"image": ImageEntityProjector(in_channels=3, out_dim=32),
                "text": VectorEntityProjector(in_dim=768, out_dim=32)},
)
scores = kg_model.score_from_kg(kg, triples[:8])
print(scores.shape)                               # torch.Size([8])

The scores above do not come from the features alone. By default MultimodalKGModel also adds a learned ID vector to every entity (add_learnable_bias=True), so it can fit training triples without using the features, and for an entity that occurs in no training triple that vector holds nothing learned from facts about it. Pass add_learnable_bias=False to build entity vectors from features only.

Know what the built-in image projector does: ImageEntityProjector averages each image over height and width and applies a linear layer, so only per-channel means survive. For real images, compute embeddings with a pretrained backbone and pass them through a VectorEntityProjector. The block above only scores triples; training, negative sampling and evaluation are in the tutorial linked above. MultimodalKGModel is Experimental. For the knowledge graph basics, see knowledge graph embedding with tensor features.


VisionServeX: Local Vision Models Upstream of a Graph

VisionServeX is a separate package from the same project: a local, license-aware gateway for running existing computer vision models, such as D-FINE or RF-DETR detectors and DINOv2 embeddings. In a graph pipeline it can sit upstream of TGraphX, producing detections or embeddings that you turn into nodes and node features. It is built for serving existing models rather than for training them, and graph neural networks are not among the model families it lists. See the VisionServeX package page.


Limitations

The layers are not vision backbones. TensorGINLayer and TensorGraphSAGELayer use 1×1 convolutions, so they never mix pixel positions inside a node. ConvMessagePassing does: its 1×1 message convolution is followed by a stack of four 3×3 convolutions. None of them is a substitute for a pretrained image model. For high-quality visual features, run a backbone (ResNet, ViT) first and apply message passing to its outputs.

Graph construction needs domain knowledge. There is no universally correct graph for an image. Patch, superpixel, object and point graphs each assume something different about which structure matters.

No built-in detector or superpixel segmentation. Bounding boxes and superpixels come from external tools (for example torchvision detection models, or SLIC in scikit-image).

Node maps must share one shape. A Graph holds all node features in one [N, C, H, W] tensor, and GraphBatch rejects graphs whose per-node shapes differ. Resize or ROI-align variable-sized crops first.


Related Articles