This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
import itertools
import numpy as np
import networkx as nx
import matplotlib.colors as col
import matplotlib.pyplot as plt
%matplotlib inline
n = 10
img = np.random.randint(size=(n, n),
low=0, high=3)
grid_2d_graph
for generating this graph.g = nx.grid_2d_graph(n, n)
def show_image(img, **kwargs):
plt.imshow(img, origin='lower',interpolation='none',
**kwargs);
plt.axis('off');
def show_graph(g, **kwargs):
nx.draw(g,
pos={(i, j): (j, i) for (i, j) in g.nodes()},
node_color=[img[i, j] for (i, j) in g.nodes()],
linewidths=1, edge_color='w', with_labels=False,
node_size=30, **kwargs);
cmap = plt.cm.Blues
plt.figure(figsize=(5,5));
show_image(img, cmap=cmap, vmin=-1);
show_graph(g, cmap=cmap, vmin=-1);
g2 = g.subgraph(zip(*np.nonzero(img==2)))
plt.figure(figsize=(5,5));
show_image(img, cmap=cmap, vmin=-1);
show_graph(g2, cmap=cmap, vmin=-1);
connected_components
function of NetworkX to find those components.components = [np.array(comp)
for comp in nx.connected_components(g2)
if len(comp)>=3]
len(components)
# We copy the image, and assign a new label
# to each found component.
img_bis = img.copy()
for i, comp in enumerate(components):
img_bis[comp[:,0], comp[:,1]] = i + 3
# We create a new discrete color map extending
# the previous map with new colors.
colors = [cmap(.5), cmap(.75), cmap(1.),
'#f4f235', '#f4a535', '#f44b35']
cmap2 = col.ListedColormap(colors, 'indexed')
plt.figure(figsize=(5,5));
show_image(img_bis, cmap=cmap2);
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).