concept
Binary mask enclosing box
Return half-open integer xyxy bounds of all foreground cells of a nonempty rectangular binary mask, or None for no foreground. A single enclosing box is not instance detection.
Formal Syntax & Structure
artificial-intelligence syntaxartificial-intelligence
mask_box(mask)Working Example
Example Snippetartificial-intelligence
def mask_box(mask): if not mask or not mask[0]: raise ValueError("empty image") width = len(mask[0]) if any(len(row) != width for row in mask): raise ValueError("ragged mask") if any(p not in (0, 1) for row in mask for p in row): raise ValueError("expected binary mask") points = [(x, y) for y, row in enumerate(mask) for x, p in enumerate(row) if p == 1] if not points: return None xs, ys = zip(*points) return [min(xs), min(ys), max(xs) + 1, max(ys) + 1]
mask = [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]print(mask_box(mask))print(mask_box([[0, 0], [0, 0]]))print(mask_box([[1, 0, 1]]))