PY-64

Label Four-Connected Regions

  • Medium–Hard
  • Image Masks
  • Python

Task

Write label_regions(mask). mask is a two-dimensional boolean NumPy array. Return (labels, regions). labels is an integer array of the same shape: background is 0, and true regions receive labels 1, 2, ... in the row-major order of their first cell. Four-connected cells share an edge; diagonals do not.

For each region append {"label", "size", "top", "left", "bottom", "right"}, where bottom and right are exclusive. Use this supplied procedure: scan cells row by row; at an unlabelled true cell, start a list worklist, repeatedly remove one pending cell, and add each in-bounds unlabelled true neighbour from up, left, right, and down. Mark a neighbour when adding it so it is added once.

Example

In [[True,False],[False,True]], the two diagonal true cells receive labels 1 and 2, each with size one.

Your implementation

You may import NumPy as np. Do not modify the mask, print, or ask for input.