diff --git a/autoarray/mask/mask_2d_util.py b/autoarray/mask/mask_2d_util.py index 00b444fbd..2151ae942 100644 --- a/autoarray/mask/mask_2d_util.py +++ b/autoarray/mask/mask_2d_util.py @@ -592,7 +592,6 @@ def blurring_mask_2d_from( ky, kx = kernel_shape_native pad_y, pad_x = ky // 2, kx // 2 - structure = np.ones((ky, kx), dtype=bool) # Unmasked region (True where unmasked) unmasked = ~mask_2d @@ -605,10 +604,18 @@ def blurring_mask_2d_from( constant_values=False, ) - # Pixels within kernel footprint of any unmasked pixel + # Pixels within kernel footprint of any unmasked pixel. The footprint is a box, + # which is separable: a (ky, 1) dilation followed by a (1, kx) dilation gives the + # same mask as one (ky, kx) dilation, without scipy's (ky * kx)**2 offsets table + # (which takes minutes and tens of GB for PSFs of a few hundred pixels). from scipy.ndimage import binary_dilation - near_unmasked_padded = binary_dilation(unmasked_padded, structure=structure) + near_unmasked_padded = binary_dilation( + unmasked_padded, structure=np.ones((ky, 1), dtype=bool) + ) + near_unmasked_padded = binary_dilation( + near_unmasked_padded, structure=np.ones((1, kx), dtype=bool) + ) near_unmasked = near_unmasked_padded[ pad_y : pad_y + mask_2d.shape[0], pad_x : pad_x + mask_2d.shape[1], diff --git a/test_autoarray/mask/test_mask_2d_util.py b/test_autoarray/mask/test_mask_2d_util.py index 89d6d6bc1..7965df89a 100644 --- a/test_autoarray/mask/test_mask_2d_util.py +++ b/test_autoarray/mask/test_mask_2d_util.py @@ -696,6 +696,29 @@ def test__blurring_mask_2d_from__mask_extends_beyond_edge_so_raises_mask_excepti util.mask_2d.blurring_mask_2d_from(mask, kernel_shape_native=(5, 5)) +@pytest.mark.parametrize( + "kernel_shape_native", + [(3, 3), (5, 3), (4, 4), (6, 2), (3, 7), (8, 5), (2, 9)], +) +def test__blurring_mask_2d_from__matches_dense_box_dilation(kernel_shape_native): + from scipy.ndimage import binary_dilation + + mask = np.full((21, 23), True) + mask[8:12, 7:15] = False + mask[13, 10] = False + + ky, kx = kernel_shape_native + unmasked = np.pad(~mask, ((ky // 2, ky // 2), (kx // 2, kx // 2))) + near = binary_dilation(unmasked, structure=np.ones((ky, kx), dtype=bool)) + near = near[ky // 2 : ky // 2 + mask.shape[0], kx // 2 : kx // 2 + mask.shape[1]] + + blurring_mask = util.mask_2d.blurring_mask_2d_from( + mask, kernel_shape_native=kernel_shape_native + ) + + assert (blurring_mask == ~(mask & near)).all() + + def test__mask_1d_indexes_from(): mask = np.array( [