Coverage for nilearn/_utils/tests/test_ndimage.py: 0%
47 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-20 10:58 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-20 10:58 +0200
1"""Test the ndimage module.
3This test file is in nilearn/tests because Nosetest,
4which we historically used,
5ignores modules whose name starts with an underscore.
6"""
8import numpy as np
9import pytest
11from nilearn._utils import data_gen
12from nilearn._utils.ndimage import largest_connected_component, peak_local_max
15def test_largest_cc():
16 """Check the extraction of the largest connected component."""
17 a = np.zeros((6, 6, 6))
18 with pytest.raises(ValueError):
19 largest_connected_component(a)
20 a[1:3, 1:3, 1:3] = 1
21 np.testing.assert_equal(a, largest_connected_component(a))
22 # A simple test with non-native dtype
23 a_change_type = a.astype(">f8")
24 np.testing.assert_equal(a, largest_connected_component(a_change_type))
26 b = a.copy()
27 b[5, 5, 5] = 1
28 np.testing.assert_equal(a, largest_connected_component(b))
29 # A simple test with non-native dtype
30 b_change_type = b.astype(">f8")
31 np.testing.assert_equal(a, largest_connected_component(b_change_type))
33 # Tests for correct errors, when an image or string are passed.
34 img = data_gen.generate_labeled_regions(shape=(10, 11, 12), n_regions=2)
36 with pytest.raises(ValueError):
37 largest_connected_component(img)
38 with pytest.raises(ValueError):
39 largest_connected_component("Test String")
42def test_empty_peak_local_max():
43 image = np.zeros((10, 20))
44 result = peak_local_max(image, min_distance=1, threshold_rel=0)
45 assert np.all(~result)
48def test_flat_peak_local_max():
49 image = np.zeros((5, 5))
50 image[1:3, 1:3] = 10
51 peaks = peak_local_max(image, min_distance=1)
52 np.testing.assert_equal(len(peaks[peaks == 1]), 4)
55def test_relative_and_absolute_thresholds_in_peak_local_max():
56 image = np.zeros((5, 5))
57 image[1, 1] = 10
58 image[3, 3] = 20
59 peaks_rel = peak_local_max(image, min_distance=1, threshold_rel=0.5)
60 np.testing.assert_equal(len(peaks_rel[peaks_rel == 1]), 1)
61 peaks_abs = peak_local_max(image, min_distance=1, threshold_abs=10)
62 np.testing.assert_equal(len(peaks_abs[peaks_abs == 1]), 1)
65def test_constant_image_in_peak_local_max():
66 image = 128 * np.ones((20, 20))
67 peaks = peak_local_max(image, min_distance=1)
68 np.testing.assert_equal(len(peaks[peaks == 1]), 0)
71def test_trivial_cases_in_peak_local_max():
72 trivial = np.zeros((25, 25))
73 peaks = peak_local_max(trivial, min_distance=1)
74 assert (peaks.astype(bool) == trivial).all()