Pixel connectivity (source code)

= Pixel connectivity

<Pixel connectivity> specifies which neighboring <pixels> may be joined directly when forming paths through an image. A region is connected when its <pixels> can be reached through such allowed steps while remaining in the region. This makes the region a <component (graph theory)> of an implicitly defined <graph>.

For a two-dimensional square grid and <pixel> position $p=(x,y)$, four-neighbor connectivity uses
$$
\mathcal N_4(p)=\{(x-1,y),(x+1,y),(x,y-1),(x,y+1)\},
$$
restricted to positions inside the image. Eight-neighbor connectivity adds the four diagonals:
$$
\mathcal N_8(p)=
\{(x+i,y+j):i,j\in\{-1,0,1\},\ (i,j)\ne(0,0)\}.
$$
Thus four-neighbor steps cross an edge between pixel cells, while eight-neighbor steps can also pass through a corner.

The diagonal <binary image>
$$
\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}
$$
has three foreground regions under four-neighbor connectivity and one under eight-neighbor connectivity. SciPy's default two-dimensional <connected-component labeling> uses the four axial neighbors; a full three-by-three neighborhood also connects diagonals. Its neighborhood must encode connections in both directions.<label in the SciPy documentation>[Parameters, structure; Notes, centrosymmetry; Examples, diagonal connectivity]{ref}

Connectivity also affects how a boundary separates foreground from background. In a two-by-two checkerboard, allowing diagonal links for both values makes each value connected across its own diagonal. A convention that treats foreground and background differently can avoid interpreting both diagonal paths as uninterrupted planar crossings. The chosen convention should therefore accompany any claim about separate objects or enclosed regions.

A <flood fill> and <connected-component labeling> can give different answers on the same stored array solely because their <pixel connectivity> differs. Check the neighborhood before interpreting that disagreement as a bug or a physical change in the imaged object.