Chapter 3. Networks of Image Regions with ndimage
Tyger Tyger, burning bright, In the forests of the night; What immortal hand or eye, Could frame thy fearful symmetry?
William Blake, The Tyger
You probably know that digital images are made up of pixels. Generally, you should not think of these as little squares, but as point samples of the light signal measured on a regular grid.1
Further, when processing images, we often deal with objects much larger than individual pixels. In a landscape, the sky, earth, trees, and rocks each span many pixels. A common structure to represent these is the region adjacency graph, or RAG. Its nodes hold properties of each region in the image, and its links hold the spatial relationships between the regions. Two nodes are linked whenever their corresponding regions touch each other in the input image.
Building such a structure could be a complicated affair, and even more difficult when images are not 2D but 3D and even 4D, as is common in microscopy, materials science, and climatology, among others. But here we will show you how to produce a RAG in a few lines of code using NetworkX (a Python library to analyze graphs and networks), and a filter from SciPy’s N-dimensional image processing submodule, ndimage.
importnetworkxasnximportnumpyasnpfromscipyimportndimageasndidefadd_edge_filter(values,graph):center=values[len(values)//2]forneighborinvalues:ifneighbor!=centerandnotgraph.has_edge(center,neighbor):graph ...