During the
raster scan of the grid, whenever an occupied cell is encountered, neighboring cells are scanned to check whether any of them have already been scanned. If we find already scanned neighbors, the union operation is performed, to specify that these neighboring cells are in fact members of the same set. Then thefind operation is performed to find a representative member of that set with which the current cell will be labeled. On the other hand, if the current cell has no neighbors, it is assigned a new, previously unused, label. The entire grid is processed in this way. Following
pseudocode is referred from Tobin Fricke's implementation of the same algorithm. On completion, the cluster labels may be found in labels. Not shown is the second raster scan of the grid needed to produce the example output. In that scan, the value at label[x,y] is replaced by find(label[x,y]).
Raster Scan and Labeling on the Grid largest_label = 0; label = zeros[n_columns, n_rows] labels = [0:n_columns*n_rows] /* Array containing integers from 0 to the size of the image. */ for x in 0 to n_columns { for y in 0 to n_rows { if occupied[x, y] then left = label[x-1, y]; above = label[x, y-1]; if (left == 0) and (above == 0) then /* Neither a label above nor to the left. */ largest_label = largest_label + 1; /* Make a new, as-yet-unused cluster label. */ label[x, y] = largest_label; else if (left != 0) and (above == 0) then /* One neighbor, to the left. */ label[x, y] = find(left); else if (left == 0) and (above != 0) then /* One neighbor, above. */ label[x, y] = find(above); else /* Neighbors BOTH to the left and above. */ union(left,above); /* Link the left and above clusters. */ label[x, y] = find(left); } }
Union void union(int x, int y) { labels[find(x)] = find(y); }
Find int find(int x) { int y = x; while (labels[y] != y) y = labels[y]; while (labels[x] != x) { int z = labels[x]; labels[x] = y; x = z; } return y; } == Example ==