|
| 1 | +"""Test for the `_util`.""" |
| 2 | + |
| 3 | + |
| 4 | +import pytest |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from skimage.morphology import _util |
| 8 | + |
| 9 | + |
| 10 | +class TestOffsetsToRaveledNeighbors: |
| 11 | + |
| 12 | + @pytest.mark.parametrize("shape", [ |
| 13 | + (111,), (33, 44), (22, 55, 11), (6, 5, 4, 3) |
| 14 | + ]) |
| 15 | + @pytest.mark.parametrize("order", ["C", "F"]) |
| 16 | + def test_highest_connectivity(self, shape, order): |
| 17 | + """ |
| 18 | + Check a scenarios where selem is always of the highest connectivity |
| 19 | + and all dimensions are > 2. |
| 20 | + """ |
| 21 | + selem = np.ones((3,) * len(shape)) |
| 22 | + center = (1,) * len(shape) |
| 23 | + offsets = _util._offsets_to_raveled_neighbors( |
| 24 | + shape, selem, center, order |
| 25 | + ) |
| 26 | + |
| 27 | + # Assert only neighbors are present (no center) |
| 28 | + assert len(offsets) == selem.sum() - 1 |
| 29 | + # Assert uniqueness |
| 30 | + assert len(set(offsets)) == offsets.size |
| 31 | + # selem of hightest connectivity is symmetric around center |
| 32 | + # -> offsets build pairs of with same value but different signs |
| 33 | + assert all(-x in offsets for x in offsets) |
| 34 | + |
| 35 | + # Construct image whose values are the Manhattan distance to its center |
| 36 | + image_center = tuple(s // 2 for s in shape) |
| 37 | + grid = np.meshgrid( |
| 38 | + *[np.abs(np.arange(s, dtype=np.intp) - c) |
| 39 | + for s, c in zip(shape, image_center)], |
| 40 | + indexing="ij" |
| 41 | + ) |
| 42 | + image = np.sum(grid, axis=0) |
| 43 | + |
| 44 | + image_raveled = image.ravel(order) |
| 45 | + image_center_raveled = np.ravel_multi_index( |
| 46 | + image_center, shape, order=order |
| 47 | + ) |
| 48 | + |
| 49 | + # Sample raveled image around its center |
| 50 | + samples = [] |
| 51 | + for offset in offsets: |
| 52 | + index = image_center_raveled + offset |
| 53 | + samples.append(image_raveled[index]) |
| 54 | + |
| 55 | + # Assert that center with value 0 wasn't selected |
| 56 | + assert np.min(samples) == 1 |
| 57 | + # Assert that only neighbors where selected |
| 58 | + # (highest value == connectivity) |
| 59 | + assert np.max(samples) == len(shape) |
| 60 | + # Assert that nearest neighbors are selected first |
| 61 | + assert list(sorted(samples)) == samples |
0 commit comments