TGraphX › Insights › Graph Learning for Computer Vision: When Image Patches Become Nodes
← Back to Insights

Graph Learning for Computer Vision: When Image Patches Become Nodes

Topic: Vision, multimodal and domain applications

The dominant paradigm for image processing is convolutional: a kernel slides over a grid of pixels, building hierarchical features through spatial locality. But not all image understanding tasks fit the grid well. When the meaningful structure in an image is relational — objects that relate to each other regardless of spatial distance, parts that form semantic groups across the image — a graph representation is worth considering.

This article covers the mechanics of turning an image into a graph with TGraphX: cutting patches, choosing edges, what a layer then does with each patch, and how large the result gets. Examples tested with TGraphX 1.5.1 on CPU with random images; the blocks build on each other, so run them in order.

When to Consider a Graph for Images

Grid convolutions are the natural choice when:

  • Spatial locality is the primary signal
  • The image has regular structure (photos, medical scans)
  • You want translation equivariance: shifting the input shifts the feature maps

Graph representations become interesting when:

  • Objects or parts need to be related across the image
  • The graph structure itself is part of the representation
  • You want to model pairwise relationships explicitly

Neither choice is better by default. Patch-graph models can be competitive on image classification (Han et al., "Vision GNN: An Image is Worth Graph of Nodes", NeurIPS 2022, is one example), but that result comes from a specific deep architecture and training recipe, not from the graph construction alone. This page measures no accuracy.

Step 1: Cut the Image into Patches

tgx.image_to_patches takes a batch of images [B, C, H, W] and returns [B, P, C, ph, pw], where P is the number of patches per image. For a single image, add a batch axis and take it off again:

python
import torch
import tgraphx as tgx
from tgraphx import Graph, GraphBatch

torch.manual_seed(0)
image = torch.randn(3, 64, 64)                        # one image [C, H, W]

patches = tgx.image_to_patches(image.unsqueeze(0), patch_size=16)[0]
print(patches.shape)                                  # torch.Size([16, 3, 16, 16])

# Row-major order: patch r * 4 + c is the block at patch row r, patch column c
assert torch.equal(patches[1], image[:, 0:16, 16:32])
assert torch.equal(patches[4], image[:, 16:32, 0:16])

Each of the 16 patches is a [3, 16, 16] tensor, and each becomes one node.

By default the image must be covered exactly. A smaller stride gives overlapping patches, and padding="auto" pads the right and bottom edges with zeros:

python
overlapping = tgx.image_to_patches(image.unsqueeze(0), patch_size=16, stride=8)[0]
print(overlapping.shape)                              # torch.Size([49, 3, 16, 16])

odd = torch.randn(1, 3, 60, 64)                       # 60 is not a multiple of 16
try:
    tgx.image_to_patches(odd, patch_size=16)
except ValueError as err:
    print("ValueError:", err)
else:
    raise AssertionError("expected a ValueError")
print(tgx.image_to_patches(odd, patch_size=16, padding="auto").shape)
# torch.Size([1, 16, 3, 16, 16])

With overlapping patches, set the grid in the next step to the patch grid (7 x 7 here), not to the image size.

Step 2: Connect the Patches with a Grid

tgx.build_grid_graph(rows, cols) returns an edge_index tensor, not a Graph. It connects horizontal and vertical neighbours only (no diagonals), adds both directions and, by default, one self-loop per node:

python
grid = tgx.build_grid_graph(4, 4)
print(grid.shape)                                          # torch.Size([2, 64])
print(tgx.build_grid_graph(4, 4, self_loops=False).shape)  # torch.Size([2, 48])

g = Graph(node_features=patches, edge_index=grid)
print(g.num_nodes, g.num_edges, g.feature_shape)           # 16 64 (3, 16, 16)
  Image (64x64) -> 4 x 4 patches of 16x16 -> 16 nodes of shape [3, 16, 16]

   0 ─  1 ─  2 ─  3
   │    │    │    │
   4 ─  5 ─  6 ─  7
   │    │    │    │
   8 ─  9 ─ 10 ─ 11
   │    │    │    │
  12 ─ 13 ─ 14 ─ 15

  24 neighbour pairs  -> 48 directed edges
  + 16 self-loops     -> 64 columns in edge_index

tgx.image_to_patch_graph does both steps at once for one image and returns a (patches, edge_index) tuple:

python
same_patches, same_grid = tgx.image_to_patch_graph(image, patch_size=16)
assert torch.equal(same_patches, patches) and torch.equal(same_grid, grid)

Step 3: Or Connect Patches by Feature Similarity

A grid cannot link two similar patches at opposite corners. A k-nearest-neighbour graph can. tgx.build_knn_graph takes a 2-D [N, D] tensor and uses Euclidean distance, so flatten the patches for the distance computation only. The node features keep their [3, 16, 16] shape.

Two defaults matter. The result is symmetrised and gets self-loops, so a node can have more than k neighbours. With directed=True, edge_index[0] holds the query patch and edge_index[1] its neighbour. Messages travel from row 0 to row 1, so flip the rows if each patch should receive from its own k neighbours:

python
flat = patches.flatten(1)                              # [16, 768], for distances only

knn_default = tgx.build_knn_graph(flat, k=4)           # symmetric, with self-loops
knn_in = tgx.build_knn_graph(flat, k=4, directed=True, self_loops=False).flip(0)
print(knn_default.shape, knn_in.shape)                 # knn_in: torch.Size([2, 64])

in_degree = torch.bincount(knn_in[1], minlength=16)
assert (in_degree == 4).all()                          # every patch receives from 4 patches

g_knn = Graph(node_features=patches, edge_index=knn_in)

Distances between raw pixels are a weak notion of similarity. Vision GNN, cited above, rebuilds its k-NN graph from learned features as the network gets deeper. If you prefer cosine similarity, tgx.knn_graph(patches, k=4) accepts the 4-D tensor directly.

To compare regions with features from a pretrained vision model instead of raw pixels, see visual similarity search from one example, which also shows where a high score is still wrong.

What a Layer Does with Patch Features

Tensor-valued nodes keep their layout, but layers differ in how pixels interact:

  • TensorGraphSAGELayer applies a 1x1 convolution to the node's own map and another to each neighbour's map, then takes the mean (or max) over neighbours and adds the two. Pixel (i, j) of the output depends only on pixel (i, j) of the inputs. TensorGINLayer is also 1x1 only.
  • ConvMessagePassing adds a stack of 3x3 convolutions after aggregation, so it does mix neighbouring pixels.

You can check this by changing one input pixel and counting the output positions that change:

python
def affected_pixels(layer):
    """Output positions of node 1 that change when one pixel of node 0 changes."""
    layer.eval()
    x = torch.randn(2, 3, 16, 16)
    edge = torch.tensor([[0], [1]])                    # node 0 -> node 1
    x_changed = x.clone()
    x_changed[0, :, 8, 8] += 5.0
    with torch.no_grad():
        delta = (layer(x, edge)[1] - layer(x_changed, edge)[1]).abs().sum(0)
    return int((delta > 1e-6).sum())

sage = tgx.TensorGraphSAGELayer(3, 8)
conv = tgx.ConvMessagePassing((3, 16, 16), (8, 16, 16), dropout_prob=0.0)
print(affected_pixels(sage), affected_pixels(conv))    # 1 81
assert affected_pixels(sage) == 1 and affected_pixels(conv) == 81   # 81 = a 9 x 9 window

So a SAGE-only network never looks at spatial patterns inside a patch. Put a small CNN or a pretrained backbone in front of it, or use a layer that convolves spatially.

Keeping Track of Position

A mean over neighbours does not depend on their order. On a grid graph, SAGE therefore cannot tell the patch on the left from the patch above, and the node features do not record where in the image a patch came from. One simple remedy is to append coordinate channels, similar in purpose to the position embedding in Vision GNN and vision transformers:

python
def add_coordinates(patches, rows, cols):
    r = torch.linspace(-1, 1, rows).repeat_interleave(cols)
    c = torch.linspace(-1, 1, cols).repeat(rows)
    coords = torch.stack([r, c], dim=1)[:, :, None, None]      # [N, 2, 1, 1]
    return torch.cat([patches, coords.expand(-1, -1, *patches.shape[-2:])], dim=1)

with_position = add_coordinates(patches, 4, 4)
print(with_position.shape)                             # torch.Size([16, 5, 16, 16])

This gives each node its absolute position. It does not make the neighbour aggregation direction-aware.

Batching Images and Classifying Them

For image classification, each image is one graph with one label. Store the label as a 0-d tensor in graph_label; GraphBatch collects them in graph_labels and builds the batch vector that maps nodes to graphs:

python
def image_to_graph(image, label, patch_size=16):
    patches, edge_index = tgx.image_to_patch_graph(image, patch_size=patch_size)
    return Graph(node_features=patches, edge_index=edge_index,
                 graph_label=torch.tensor(label))

images = torch.randn(32, 3, 64, 64)                    # synthetic images
labels = torch.randint(0, 10, (32,)).tolist()
batch = GraphBatch([image_to_graph(img, lbl) for img, lbl in zip(images, labels)])
print(batch.node_features.shape)                       # torch.Size([512, 3, 16, 16])
print(batch.graph_labels.shape)                        # torch.Size([32])

model = tgx.build_model("graph_classification", layer="sage", in_shape=(3, 16, 16),
                        hidden_shape=(16, 16, 16), num_layers=2, num_classes=10)
logits = model(batch.node_features, batch.edge_index, batch=batch.batch)
print(logits.shape)                                    # torch.Size([32, 10])

loss = torch.nn.functional.cross_entropy(logits, batch.graph_labels)
loss.backward()

This model averages away the spatial axes and then averages over the patches of each image before the linear head. Anything about position has to reach the node features through the layers or through coordinate channels.

For a version trained on real data, with a train/validation/test split and a flat-vector baseline, see CIFAR-10 patch graphs. The MNIST as a graph tutorial shows the node-labelled variant and why the split must be made by image.

How Large the Graphs Get

A 224x224 image with 16x16 patches gives 196 nodes. The 14 x 14 grid has 728 neighbour edges, or 924 with self-loops. A directed k-NN graph with k=8 and no self-loops has 196 x 8 = 1568 edges.

The node count is small, but each edge carries a whole feature map. The message buffer scales with E * C * H * W:

python
print(tgx.build_grid_graph(14, 14, self_loops=False).shape[1],
      tgx.build_grid_graph(14, 14).shape[1])           # 728 924

for channels in (3, 64):
    est = tgx.estimate_message_memory(num_edges=1568, out_shape=(channels, 16, 16))
    print(channels, est["total_mb"])
# 3 4.594
# 64 98.0

per_batch = tgx.estimate_message_memory(num_edges=32 * 1568, out_shape=(64, 16, 16))
print(per_batch["total_mb"])                           # 3136.0

Those figures are in MiB, for one layer's float32 messages only; activations and gradients come on top. At 64 channels and 16x16 resolution, a batch of 32 such images needs about 3 GiB for messages alone. Downsample the patches or reduce channels before message passing if that is too much.

To build graphs from pixels, superpixels or regions as well as patches, see how to convert an image into a graph in Python.

Summary

  • image_to_patches works on batches; image_to_patch_graph on single images.
  • Grid builders return edge_index tensors, 4-connected, with self-loops by default.
  • Check which way k-NN edges point before using them directed.
  • SAGE and GIN never mix pixel positions; ConvMessagePassing does.
  • Add position information if it matters, and estimate message memory before scaling up.

For turning the per-node maps into one prediction per image, see graph-level tensors, pooling and readout.