TGraphX › Insights › How to Convert an Image into a Graph in Python
← Back to Insights

How to Convert an Image into a Graph in Python

Topic: Images as graphs

To turn an image into a graph, decide what one node is (a pixel, a square patch, a superpixel or an object), compute a feature array for every node, and list which pairs of nodes are joined. The result is usually two arrays: node features x with one row or tensor per node, and edge_index of shape [2, E], where column k says that node edge_index[0, k] sends to node edge_index[1, k]. No special library is needed for this step: NumPy, PyTorch and scikit-image are enough, and the same two arrays load into graph neural network libraries afterwards.

If you meant something else by "image to graph", such as reading the data values out of a picture of a chart or tracing a drawing into plot equations, this page is not about that. Here a graph means nodes and edges.

Three choices define the graph

Nothing in a photograph says what its nodes are. You choose, and the choice matters more than the code.

One node is Nodes for a 512 x 512 image Typical node features Natural edges
a pixel 262,144 colour values 4 or 8 grid neighbours
a 32 x 32 patch 256 the patch tensor, or an encoder's vector grid neighbours or nearest features
a superpixel one or two hundred in the example below mean colour, position, size regions that touch
an object as many as are found box, shape, appearance nearest or overlapping objects

The other two choices, node features and edges, are independent of each other. You can join patches by where they are or by what they look like, and still store the same patch tensor on each node.

Setup

The examples need numpy, torch and scikit-image. The image is the astronaut photograph that ships with scikit-image, so nothing is downloaded.

python
import numpy as np
import torch
from skimage import data as skdata

img = skdata.astronaut().astype(np.float32) / 255.0     # [H, W, C], values in [0, 1]
H, W, C = img.shape
print(img.shape)                                        # (512, 512, 3)

For your own file, use np.asarray(Image.open("photo.jpg").convert("RGB"), dtype=np.float32) / 255.0 with from PIL import Image. The conversion to RGB removes the alpha channel of many PNG files and turns grey images into three channels, so every image gives features of the same width.

Pixels and patches both sit on a grid, so one helper produces the edges of both. It returns every neighbour pair in both directions and no self-loops.

python
def grid_edges(rows, cols, diagonal=False):
    """Directed edge_index [2, E] of a rows x cols grid, nodes numbered row by row."""
    idx = np.arange(rows * cols).reshape(rows, cols)
    pairs = [(idx[:, :-1], idx[:, 1:]),                 # left and right
             (idx[:-1, :], idx[1:, :])]                 # up and down
    if diagonal:
        pairs += [(idx[:-1, :-1], idx[1:, 1:]),         # down-right
                  (idx[:-1, 1:], idx[1:, :-1])]         # down-left
    a = np.concatenate([p.ravel() for p, _ in pairs])
    b = np.concatenate([q.ravel() for _, q in pairs])
    return np.stack([np.concatenate([a, b]), np.concatenate([b, a])])

print(grid_edges(2, 2).T.tolist())
# [[0, 1], [2, 3], [0, 2], [1, 3], [1, 0], [3, 2], [2, 0], [3, 1]]

A four-node example you can check by hand

Take a 4 x 4 grey image and cut it into four 2 x 2 patches:

text
 image                      node = patch           grid edges

  10  10 | 200 200
  10  10 | 200 200            0 | 1                  0 --- 1
  --------+--------           --+--                  |     |
  10  90 |  30  30            2 | 3                  2 --- 3
  90  90 |  30  30

Give each node the mean of its patch: node 0 has 10, node 1 has 200, node 2 has (10 + 90 + 90 + 90) / 4 = 70 and node 3 has 30. Now let every node take the average of the nodes that send to it. Node 0 hears from 1 and 2, so it gets (200 + 70) / 2 = 135. Node 1 hears from 0 and 3 and gets (10 + 30) / 2 = 20.

That averaging step, repeated with learned weights, is what a graph neural network does with your graph. In symbols, with N(j) the set of nodes that send to node j and x_i the features of node i:

a_j = (1 / |N(j)|) × sum of x_i over i in N(j)

The same function works whether a node holds a number, a vector or a whole patch tensor:

python
def mean_neighbors(x, edge_index):
    """a_j: mean of the features of every node that sends to j."""
    src, dst = edge_index
    total = torch.zeros_like(x).index_add_(0, dst, x[src])
    count = torch.bincount(dst, minlength=len(x)).clamp(min=1)
    return total / count.view(-1, *[1] * (x.dim() - 1))

tiny = torch.tensor([[10, 10, 200, 200], [10, 10, 200, 200],
                     [10, 90,  30,  30], [90, 90,  30,  30]], dtype=torch.float32)
blocks = tiny.unfold(0, 2, 2).unfold(1, 2, 2).reshape(4, 2, 2)     # four 2 x 2 patches
tiny_edges = torch.from_numpy(grid_edges(2, 2))

means = blocks.mean(dim=(1, 2))
print(means.tolist())                                  # [10.0, 200.0, 70.0, 30.0]
print(mean_neighbors(means, tiny_edges).tolist())      # [135.0, 20.0, 20.0, 135.0]
print(mean_neighbors(blocks, tiny_edges)[0].tolist())  # [[105.0, 145.0], [145.0, 145.0]]

The last line averages the patches themselves instead of their means. The result for node 0 is still a 2 x 2 block, and its top-left value is lower because patch 2 is dark in that corner.

Pixels as nodes

The most literal conversion makes every pixel a node. It is easy and it gets large fast, so the example takes every eighth pixel first.

python
small = img[::8, ::8]                          # 64 x 64, for illustration
h, w = small.shape[:2]

x_pix = torch.from_numpy(small.reshape(h * w, C).copy())     # [4096, 3]
e_pix = torch.from_numpy(grid_edges(h, w))                    # 4-neighbour
e_pix8 = torch.from_numpy(grid_edges(h, w, diagonal=True))    # 8-neighbour
rows_ix, cols_ix = np.indices((h, w))
pos_pix = torch.from_numpy(np.stack([rows_ix.ravel(), cols_ix.ravel()], axis=1))

print(x_pix.shape, e_pix.shape, e_pix8.shape)
# torch.Size([4096, 3]) torch.Size([2, 16128]) torch.Size([2, 32004])
print(grid_edges(H, W).shape)                  # full resolution: (2, 1046528)

For an H x W grid the number of directed edges is 2 × (H(W − 1) + W(H − 1)) with four neighbours, plus 4 × (H − 1)(W − 1) with diagonals. At full resolution that is over a million edges for one image, and with 64-bit indices the edge_index alone (about 16.7 MB) is larger than the float32 pixels (about 3.1 MB). If all you want is mixing between adjacent pixels, a convolution does it without storing any edges. A pixel graph is worth building when the edges are not the plain grid: an irregular mask, a region of interest, or links that depend on the pixel values.

Patches as nodes

Cutting the image into square patches is a common middle ground, used for example by the Vision GNN architecture (Han and others, 2022). Tensor.unfold does it without loops.

python
t = torch.from_numpy(img).permute(2, 0, 1)             # [C, H, W]
p = 32                                                  # patch side in pixels
rows, cols = H // p, W // p                             # 16 x 16

patches = (t.unfold(1, p, p).unfold(2, p, p)            # [C, rows, cols, p, p]
             .permute(1, 2, 0, 3, 4)
             .reshape(rows * cols, C, p, p))            # [N, C, p, p]

assert torch.equal(patches[1], t[:, 0:p, p:2 * p])      # node 1: first row, second column
assert torch.equal(patches[cols], t[:, p:2 * p, 0:p])   # node 16: second row, first column

e_grid = torch.from_numpy(grid_edges(rows, cols))
print(patches.shape, e_grid.shape)
# torch.Size([256, 3, 32, 32]) torch.Size([2, 960])

If the image side is not a multiple of p, unfold silently drops the remainder at the right and bottom. Resize, crop or pad on purpose before this step.

Each node now holds a [3, 32, 32] tensor. You can keep it that way or call patches.flatten(1) to get a [256, 3072] matrix for a layer that expects vectors. Flattening is reversible as long as you remember the shape. What changes is whether later layers use the arrangement of the pixels.

Edges by appearance instead of position

A grid only joins patches that touch. To join patches that look alike, compare their features and keep the k nearest. The raw pixel distance is a crude measure of likeness, so this example compares mean colours.

python
def knn_edges(feats, k):
    """Each node receives from its k nearest nodes (itself excluded)."""
    d = torch.cdist(feats, feats)
    d.fill_diagonal_(float("inf"))
    senders = d.topk(k, largest=False).indices                    # [N, k]
    receivers = torch.arange(len(feats)).repeat_interleave(k)
    return torch.stack([senders.reshape(-1), receivers])

mean_rgb = patches.mean(dim=(2, 3))                    # [256, 3]
e_knn = knn_edges(mean_rgb, k=8)

grid_row, grid_col = e_knn // cols, e_knn % cols
steps = (grid_row[0] - grid_row[1]).abs() + (grid_col[0] - grid_col[1]).abs()
print(e_knn.shape)                                     # torch.Size([2, 2048])
print(round(steps.float().mean().item(), 1))           # 7.2
print(round((steps == 1).float().mean().item(), 2))    # 0.09

On this photograph the colour neighbours of a patch are on average 7.2 grid steps away, and only 9 percent of these edges join patches that share a side. The two edge rules therefore describe very different graphs over identical nodes. Note also the direction: every node receives from exactly 8 others, but how many nodes it sends to varies.

Try it: patch size and edge rule

The lab below works on three small grey images. Change the patch size to see the node count and the feature size per node trade against each other, then switch the edge rule and watch which patches stay connected.

Image to patch graph: patch size and edge rule

0123456789101112131415

Dashed lines cut the image into patches; each circle is a node.Thick arrows run into the selected node (solid ring) from its neighbours (dashed rings).Thin lines join the other connected pairs.An edge bends around a node that it does not join.

Direction: an edge j → i means that node i receives from node j. No self-loops. Position is measured between patch centres, in patches; kNN ties go to the lower node number.

selected node
0 (patch row 0, column 0)
receives from
1, 4
sends to
1, 4
feature shape [C, p, p]
[1, 2, 2]
nodes
16
directed edges
48
raw node features, float32
16 × 1 × 2 × 2 × 4 B = 256 B
every edge has a reverse
yes

Features of node 0: shape [1, 2, 2], grey values 0 to 255

230230
230230
Counts for the 8 × 8 image at every patch size (directed edges)
quantity2 × 24 × 4
nodes164
shape per node[1, 2, 2][1, 4, 4]
raw features (B)256256
edges, grid-4488
edges, grid-88412
edges, kNN by position (k = 2)328
edges, kNN by feature (k = 2)328
edges, radius (r = 1.5)8412

Image bright corners, 2 × 2 patches, grid-4: 16 nodes, 48 directed edges. Node 0 receives from: 1, 4.

Pick an image, a patch size and an edge rule, then select nodes. Compare feature neighbours with position neighbours, starting with node 0 of the bright corners image. Illustrative grey values chosen by the author: not a photograph, a dataset or model output. Patches, edges, counts and bytes are computed from them by the stated rules. The bytes count raw float32 node features only; patches do not overlap, so that number does not depend on the patch size.

Superpixels as nodes

Squares ignore image content. Superpixels are small regions of similar, nearby pixels, so their outlines tend to follow edges in the picture. SLIC (Achanta and others, 2012) is available in scikit-image.

python
from skimage.segmentation import slic

labels = slic(img, n_segments=250, compactness=10, start_label=0, channel_axis=-1)
N = int(labels.max()) + 1
assert np.array_equal(np.unique(labels), np.arange(N))
print(labels.shape, N)                                  # (512, 512) 184

n_segments is a request, not a promise: here 250 became 184. Pass start_label=0, because the default is 1 and node indices must start at 0.

A superpixel has an irregular shape and a variable number of pixels, so it needs summary features. Mean colour, centre position and relative area are a reasonable start:

python
flat = labels.ravel()
count = np.bincount(flat, minlength=N)
rr, cc = np.indices(labels.shape)

mean_color = np.stack([np.bincount(flat, img[..., k].ravel(), N) for k in range(C)], 1)
mean_color /= count[:, None]
centroid = np.stack([np.bincount(flat, rr.ravel(), N), np.bincount(flat, cc.ravel(), N)], 1)
centroid /= count[:, None] * np.array([H, W])           # row and column in [0, 1]
area = count[:, None] / (H * W)

x_sp = torch.from_numpy(np.concatenate([mean_color, centroid, area], 1)).float()
print(x_sp.shape)                                       # torch.Size([184, 6])

For edges, join two superpixels when a pixel of one is directly beside or below a pixel of the other. This is called a region adjacency graph.

python
def region_adjacency(labels):
    a = np.concatenate([labels[:, :-1].ravel(), labels[:-1, :].ravel()])
    b = np.concatenate([labels[:, 1:].ravel(), labels[1:, :].ravel()])
    touching = np.stack([a[a != b], b[a != b]], axis=1)
    pairs = np.unique(np.sort(touching, axis=1), axis=0)          # each pair once
    return np.concatenate([pairs, pairs[:, ::-1]]).T              # both directions

e_sp = torch.from_numpy(region_adjacency(labels).copy())
print(e_sp.shape)                                       # torch.Size([2, 980])

from skimage import graph as skgraph
rag = skgraph.rag_mean_color(img, labels, connectivity=1)
theirs = {(min(u, v), max(u, v)) for u, v in rag.edges() if u != v}
ours = {(int(u), int(v)) for u, v in e_sp.T.tolist() if u < v}
print(len(ours), theirs == ours)                        # 490 True

The second half of the block checks the hand-written function against scikit-image's own region adjacency graph: both find the same 490 neighbouring pairs. Keep connectivity=1 if you want that match. The default of rag_mean_color is 2, which also joins regions that meet only diagonally (493 pairs here).

Objects or regions as nodes

When the things you care about are countable objects, make each one a node. The nodes can come from a detector, a segmentation model or, for simple pictures, classical segmentation. The next block separates the coins in another bundled image with marker-based watershed.

python
from scipy import ndimage as ndi
from skimage import filters, measure, segmentation

coins = skdata.coins()                                  # [303, 384], grey
markers = np.zeros(coins.shape, dtype=int)
markers[coins < 30] = 1                                 # surely background
markers[coins > 150] = 2                                # surely coin
seg = segmentation.watershed(filters.sobel(coins), markers)
blobs = measure.label(ndi.binary_fill_holes(seg == 2))
props = [r for r in measure.regionprops(blobs, intensity_image=coins) if r.area > 100]

x_obj = torch.tensor([[r.area / coins.size, r.intensity_mean / 255, r.eccentricity]
                      for r in props], dtype=torch.float32)
pos_obj = torch.tensor([r.centroid for r in props], dtype=torch.float32)
pos_obj /= torch.tensor(coins.shape, dtype=torch.float32)
e_obj = knn_edges(pos_obj, k=3)                         # three nearest objects

print(len(props), x_obj.shape, e_obj.shape)
# 24 torch.Size([24, 3]) torch.Size([2, 72])

The thresholds 30 and 150 were picked for this image, and the area filter removes a speck of a few pixels. With a trained detector, x_obj would hold box coordinates, class scores or features cropped from the network, and the edge rule could use box overlap. Whatever produces the objects sets the ceiling: a missed object has no node, and no edge can recover it.

Hand the graph to a library

All four conversions now have the same form, so moving into a library is short. With PyTorch Geometric:

python
from torch_geometric.data import Data

g_sp = Data(x=x_sp, edge_index=e_sp, pos=torch.from_numpy(centroid).float())
print(g_sp)                      # Data(x=[184, 6], edge_index=[2, 980], pos=[184, 2])
print(g_sp.validate())           # True

PyTorch Geometric also has a ToSLIC transform, which takes a [C, H, W] tensor and returns superpixel mean colours and centre positions. It does not create edges, so you still have to choose them:

python
from torch_geometric.transforms import ToSLIC

auto = ToSLIC(n_segments=250, compactness=10)(t)
print(auto.x.shape, auto.pos.shape, auto.edge_index)
# torch.Size([184, 3]) torch.Size([184, 2]) None

Keeping the patch as a tensor

The [256, 3, 32, 32] patch tensor can go through a layer without being flattened. PyTorch Geometric stores tensor-valued x, though most of its built-in convolutions expect vectors, so there you would write the layer yourself. TGraphX, a Beta library maintained by this site's author, ships a few layers for this case (see why tensor-valued node shape matters):

python
import tgraphx as tgx
from tgraphx import Graph

torch.manual_seed(0)
g = Graph(node_features=patches, edge_index=e_grid)
layer = tgx.TensorGraphSAGELayer(3, 8)                  # 1 x 1 convolutions per position
with torch.no_grad():
    out = layer(g.node_features, g.edge_index)
print(g.num_nodes, g.num_edges, out.shape)
# 256 960 torch.Size([256, 8, 32, 32])

This layer combines pixel (r, c) of a patch only with pixel (r, c) of its neighbours, so it does not mix positions inside a patch. TGraphX also does not find superpixels or objects for you. For more on patch graphs in that library, see Graph Learning for Computer Vision, and for scene, patch and nearest-neighbour recipes, Building Vision Graphs.

What it costs in memory

python
def megabytes(tensor):
    return tensor.numel() * tensor.element_size() / 1e6

print(round(megabytes(t), 2), round(megabytes(patches), 2))      # 3.15 3.15
print(round(megabytes(e_grid), 3), round(megabytes(out), 2))     # 0.015 8.39

Cutting non-overlapping patches stores the same numbers as the image. The growth comes later. A message-passing layer that builds one message per edge needs about E × C_out × p × p values for patch messages: with 960 edges, 8 output channels and 32 x 32 patches that is about 31 MB in float32 for a single layer and a single image, before gradients. Superpixel and object graphs are far smaller because each node is a short vector.

Check the graph and add edge information

A wrong index rarely raises an error at the point where you made it, so test the arrays once after building them. Indices must lie in range, there should be no accidental self-loops or repeated edges, and a graph that is meant to be undirected must contain every edge in both directions.

python
def check_graph(x, edge_index, undirected=True):
    assert edge_index.dtype == torch.long and edge_index.shape[0] == 2
    assert edge_index.min() >= 0 and edge_index.max() < len(x)
    pairs = set(map(tuple, edge_index.T.tolist()))
    assert len(pairs) == edge_index.shape[1], "repeated edge"
    assert all(i != j for i, j in pairs), "self-loop"
    if undirected:
        assert all((j, i) in pairs for i, j in pairs), "missing reverse edge"
    return len(x), edge_index.shape[1], len(x) - len(edge_index[1].unique())

for name, x, e, undirected in [("pixels", x_pix, e_pix, True), ("patch grid", patches, e_grid, True),
                               ("patch kNN", patches, e_knn, False), ("superpixels", x_sp, e_sp, True),
                               ("coins", x_obj, e_obj, False)]:
    print(name, check_graph(x, e, undirected))          # nodes, edges, nodes that receive nothing
# pixels (4096, 16128, 0)
# patch grid (256, 960, 0)
# patch kNN (256, 2048, 0)
# superpixels (184, 980, 0)
# coins (24, 72, 0)

Edges can carry data as well. For spatial graphs a common choice is the position of the sender relative to the receiver, pos[sender] - pos[receiver], which tells a model on which side a neighbour lies. Without it, a message from the left looks exactly like a message from the right.

python
src, dst = e_sp
pos = torch.from_numpy(centroid).float()
offset = pos[src] - pos[dst]                            # [E, 2]: row and column difference
distance = offset.norm(dim=1, keepdim=True)
edge_attr = torch.cat([offset, distance], dim=1)
print(edge_attr.shape)                                  # torch.Size([980, 3])

Check that the layer you plan to use reads edge features. Many accept only a scalar weight, or ignore extra arguments unless they were configured for them.

Which representation should you use?

  • Pixels: when the output is per pixel and the connectivity is unusual (inside a mask, along thin structures). For ordinary local mixing, use a convolution.
  • Patches: when you want every part of the image covered, a fixed number of nodes and simple batching. Boundaries will cut through patches.
  • Superpixels: when region outlines matter and a short feature vector per region is enough. Node count and shape differ from image to image, and results depend on SLIC settings.
  • Objects: when the question is about things and their relations (which cup is on which table). You depend on the detector.
  • No graph: when the task is classifying a whole image and you have no relation to express, a CNN or a vision transformer is the simpler starting point.

Mistakes that still run but give the wrong graph

  1. Reversed direction. topk returns, for each node, its neighbours. To make the node receive from them, the neighbours go in row 0 and the node in row 1.
  2. One direction only. Listing each grid pair once means information travels right and down but never back.
  3. Counting a node twice. If a layer already has a separate term for the node itself, as PyTorch Geometric's SAGEConv and GINConv do, a self-loop in edge_index brings the node in a second time. PyG's GCNConv adds self-loops by default and does not duplicate ones you supply, but not every library does the same. Check the layer before adding your own.
  4. Labels used as indices. Superpixel or region labels that start at 1, or have gaps after filtering, must be renumbered to 0 .. N-1.
  5. Features on different scales. Pixel areas in the thousands next to colours in [0, 1] will dominate any distance used to build edges.
  6. Lost position. Message passing does not know where a node was. If layout matters, add coordinates to the features or to the edge features.
  7. Leaky splits. When training on many images, split by image. Putting patches of one image in both training and test inflates the score.

What the graph does not give you

The conversion creates no information. Every number on a node came from the pixels, and the edges are your assumption about which parts should exchange it. A model on this graph can be better, equal or worse than a CNN on the same data; only a held-out comparison on your task answers that. Compare against a baseline with the same node features and no edges, too: if the scores match, the edges are not helping.

Two practical cautions apply to the code above. SLIC settings and the watershed thresholds were chosen for these two images and will need adjusting for yours. And a graph built from raw colours has no notion of objects or meaning. For that, take node features from a trained network.

References

The code was run on a CPU with scikit-image 0.26, PyTorch 2.15, PyTorch Geometric 2.8.1 and TGraphX 1.5.1. Other versions of SLIC may produce a slightly different number of superpixels.