import numpy as np from scipy.ndimage import maximum_filter, minimum_filter def partition(mask, visible, *, width=3): mask, visible = np.asarray(mask, bool), np.asarray(visible, bool) if mask.shape != visible.shape or mask.ndim not in (2, 3): raise ValueError('mask and V must be matching HW or NHW arrays') if type(width) is not int or width < 0: raise ValueError('boundary width must be a nonnegative integer radius') size = (1,) * (mask.ndim - 2) + (2 * width + 1, 2 * width + 1) boundary = maximum_filter(mask, size=size, mode='nearest') ^ minimum_filter(mask, size=size, mode='nearest') scored = ~boundary return dict(observed=scored & (~mask | visible), unobserved=scored & mask & ~visible)