From 5686e11c97e5855e074a677a249285f546713f63 Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Thu, 21 Feb 2013 17:17:58 +1100 Subject: [PATCH 1/9] Add funct to remove small connected compononents --- skimage/morphology/__init__.py | 1 + skimage/morphology/misc.py | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 skimage/morphology/misc.py diff --git a/skimage/morphology/__init__.py b/skimage/morphology/__init__.py index d4c775eb..e93d22ad 100644 --- a/skimage/morphology/__init__.py +++ b/skimage/morphology/__init__.py @@ -7,3 +7,4 @@ from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction +from .misc import remove_small_connected_components diff --git a/skimage/morphology/misc.py b/skimage/morphology/misc.py new file mode 100644 index 00000000..159a3a3b --- /dev/null +++ b/skimage/morphology/misc.py @@ -0,0 +1,40 @@ +import numpy as np +import scipy.ndimage as nd + +def remove_small_connected_components(ar, min_size=64, + connectivity=1, in_place=False): + """Remove connected components smaller than the specified size. + + Parameters + ---------- + ar : ndarray (arbitrary shape, int or bool type) + The array containing the connected components of interest. + min_size : int, optional (default: 64) + The smallest allowable connected component size. + connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) + The connectivity defining the neighborhood of a pixel. + in_place : bool, optional (default: False) + If `True`, remove the connected components in the input array itself. + Otherwise, make a copy. + + Returns + ------- + out : ndarray, same shape and type as input `ar` + The input array with small connected components removed. + """ + structuring_element = nd.generate_binary_structure(ar.ndim, connectivity) + if in_place: + out = ar + else: + out = ar.copy() + if min_size == 0: # shortcut for efficiency + return out + if out.dtype == bool: + ccs = nd.label(ar, structuring_element)[0] + else: + ccs = out + component_sizes = np.bincount(ccs.ravel()) + too_small = component_sizes < min_size + too_small_mask = too_small[ccs] + out[too_small_mask] = 0 + return out From 24b14508c804446f40ba1fdf4007ce35c7c7ec77 Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Sun, 3 Mar 2013 14:34:14 +1100 Subject: [PATCH 2/9] Add examples to docstring --- skimage/morphology/misc.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/skimage/morphology/misc.py b/skimage/morphology/misc.py index 159a3a3b..81f47e9c 100644 --- a/skimage/morphology/misc.py +++ b/skimage/morphology/misc.py @@ -21,6 +21,28 @@ def remove_small_connected_components(ar, min_size=64, ------- out : ndarray, same shape and type as input `ar` The input array with small connected components removed. + + Examples + -------- + >>> import numpy as np + >>> from skimage import morphology + >>> from scipy import ndimage as nd + >>> a = np.array([[0, 0, 0, 1, 0], + ... [1, 1, 1, 0, 0], + ... [1, 1, 1, 0, 1]], bool) + >>> b = morphology.remove_small_connected_components(a, 6) + >>> b + array([[False, False, False, False, False], + [ True, True, True, False, False], + [ True, True, True, False, False]], dtype=bool) + >>> c = morphology.remove_small_connected_components(a, 7, connectivity=2) + >>> c + array([[False, False, False, True, False], + [ True, True, True, False, False], + [ True, True, True, False, False]], dtype=bool) + >>> d = morphology.remove_small_connected_components(a, 6, in_place=True) + >>> d is a + True """ structuring_element = nd.generate_binary_structure(ar.ndim, connectivity) if in_place: From 5222fb5ff7eef0115603e99d8f266eda884fb141 Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Sun, 3 Mar 2013 14:50:20 +1100 Subject: [PATCH 3/9] Add tests for remove_small_connected_components --- skimage/morphology/tests/test_misc.py | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 skimage/morphology/tests/test_misc.py diff --git a/skimage/morphology/tests/test_misc.py b/skimage/morphology/tests/test_misc.py new file mode 100644 index 00000000..77bb20c3 --- /dev/null +++ b/skimage/morphology/tests/test_misc.py @@ -0,0 +1,30 @@ +import numpy as np +from numpy.testing import assert_array_equal, assert_equal +from skimage.morphology import remove_small_connected_components + +test_image = np.array([[0, 0, 0, 1, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 1]], bool) +def test_one_connectivity(): + expected = np.array([[0, 0, 0, 0, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0]], bool) + observed = remove_small_connected_components(test_image, min_size=6) + assert_array_equal(observed, expected) + +def test_two_connectivity(): + expected = np.array([[0, 0, 0, 1, 0], + [1, 1, 1, 0, 0], + [1, 1, 1, 0, 0]], bool) + observed = remove_small_connected_components(test_image, min_size=7, + connectivity=2) + assert_array_equal(observed, expected) + +def test_in_place(): + observed = remove_small_connected_components(test_image, min_size=6, + in_place=True) + assert_equal(observed is test_image, True, + "remove_small_connected_components in_place argument failed.") + +if __name__ == "__main__": + np.testing.run_module_suite() From afed313369e332f2c7b64bcb9e65582126016a4e Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Sun, 3 Mar 2013 15:18:12 +1100 Subject: [PATCH 4/9] Modify example to use remove_small_connected_components --- doc/examples/applications/plot_coins_segmentation.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/doc/examples/applications/plot_coins_segmentation.py b/doc/examples/applications/plot_coins_segmentation.py index f46bbd33..943c57fb 100644 --- a/doc/examples/applications/plot_coins_segmentation.py +++ b/doc/examples/applications/plot_coins_segmentation.py @@ -90,12 +90,8 @@ plt.title('Filling the holes') Small spurious objects are easily removed by setting a minimum size for valid objects. """ - -label_objects, nb_labels = ndimage.label(fill_coins) -sizes = np.bincount(label_objects.ravel()) -mask_sizes = sizes > 20 -mask_sizes[0] = 0 -coins_cleaned = mask_sizes[label_objects] +from skimage import morphology +coins_cleaned = morphology.remove_small_connected_components(fill_coins, 21) plt.figure(figsize=(4, 3)) plt.imshow(coins_cleaned, cmap=plt.cm.gray, interpolation='nearest') @@ -149,8 +145,7 @@ plt.title('markers') Finally, we use the watershed transform to fill regions of the elevation map starting from the markers determined above: """ -from skimage.morphology import watershed -segmentation = watershed(elevation_map, markers) +segmentation = morphology.watershed(elevation_map, markers) plt.figure(figsize=(4, 3)) plt.imshow(segmentation, cmap=plt.cm.gray, interpolation='nearest') From d6c5ba38ef03bd9e3c9f82bd1c724ea06ebc7f11 Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Sun, 3 Mar 2013 20:33:05 +1100 Subject: [PATCH 5/9] Improve docstring for remove_small_connected_components - Explain behavior if input is of int type. - Add `Raises` section for possible errors. - Remove explicit numpy import from example. --- skimage/morphology/misc.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/skimage/morphology/misc.py b/skimage/morphology/misc.py index 81f47e9c..d70e8eb8 100644 --- a/skimage/morphology/misc.py +++ b/skimage/morphology/misc.py @@ -2,13 +2,15 @@ import numpy as np import scipy.ndimage as nd def remove_small_connected_components(ar, min_size=64, - connectivity=1, in_place=False): + connectivity=1, in_place=False): """Remove connected components smaller than the specified size. Parameters ---------- ar : ndarray (arbitrary shape, int or bool type) - The array containing the connected components of interest. + The array containing the connected components of interest. If the array + type is int, it is assumed that it contains already-labeled objects. + The ints must be non-negative. min_size : int, optional (default: 64) The smallest allowable connected component size. connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1) @@ -17,6 +19,13 @@ def remove_small_connected_components(ar, min_size=64, If `True`, remove the connected components in the input array itself. Otherwise, make a copy. + Raises + ------ + ValueError + If the input array is of int type but contains negative values. + TypeError + If the input array is of an invalid type, such as float or string. + Returns ------- out : ndarray, same shape and type as input `ar` @@ -24,7 +33,6 @@ def remove_small_connected_components(ar, min_size=64, Examples -------- - >>> import numpy as np >>> from skimage import morphology >>> from scipy import ndimage as nd >>> a = np.array([[0, 0, 0, 1, 0], From b07f7fd9bd910784ee14f08800765d3276b1e6fa Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Sun, 3 Mar 2013 20:47:02 +1100 Subject: [PATCH 6/9] Rename function to remove_small_objects --- skimage/morphology/__init__.py | 2 +- skimage/morphology/misc.py | 3 +-- skimage/morphology/tests/test_misc.py | 10 +++++----- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/skimage/morphology/__init__.py b/skimage/morphology/__init__.py index e93d22ad..044fcf89 100644 --- a/skimage/morphology/__init__.py +++ b/skimage/morphology/__init__.py @@ -7,4 +7,4 @@ from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image from .greyreconstruct import reconstruction -from .misc import remove_small_connected_components +from .misc import remove_small_objects diff --git a/skimage/morphology/misc.py b/skimage/morphology/misc.py index d70e8eb8..719fba5a 100644 --- a/skimage/morphology/misc.py +++ b/skimage/morphology/misc.py @@ -1,8 +1,7 @@ import numpy as np import scipy.ndimage as nd -def remove_small_connected_components(ar, min_size=64, - connectivity=1, in_place=False): +def remove_small_objects(ar, min_size=64, connectivity=1, in_place=False): """Remove connected components smaller than the specified size. Parameters diff --git a/skimage/morphology/tests/test_misc.py b/skimage/morphology/tests/test_misc.py index 77bb20c3..f27b1a45 100644 --- a/skimage/morphology/tests/test_misc.py +++ b/skimage/morphology/tests/test_misc.py @@ -1,6 +1,6 @@ import numpy as np from numpy.testing import assert_array_equal, assert_equal -from skimage.morphology import remove_small_connected_components +from skimage.morphology import remove_small_objects test_image = np.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], @@ -9,22 +9,22 @@ def test_one_connectivity(): expected = np.array([[0, 0, 0, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]], bool) - observed = remove_small_connected_components(test_image, min_size=6) + observed = remove_small_objects(test_image, min_size=6) assert_array_equal(observed, expected) def test_two_connectivity(): expected = np.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]], bool) - observed = remove_small_connected_components(test_image, min_size=7, + observed = remove_small_objects(test_image, min_size=7, connectivity=2) assert_array_equal(observed, expected) def test_in_place(): - observed = remove_small_connected_components(test_image, min_size=6, + observed = remove_small_objects(test_image, min_size=6, in_place=True) assert_equal(observed is test_image, True, - "remove_small_connected_components in_place argument failed.") + "remove_small_objects in_place argument failed.") if __name__ == "__main__": np.testing.run_module_suite() From 6b9ecd80b91ad4c2ded3536ac34d21d09ba33bc8 Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Sun, 3 Mar 2013 21:43:56 +1100 Subject: [PATCH 7/9] Add raise and labeled image tests --- skimage/morphology/tests/test_misc.py | 36 +++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/skimage/morphology/tests/test_misc.py b/skimage/morphology/tests/test_misc.py index f27b1a45..4b6e6e01 100644 --- a/skimage/morphology/tests/test_misc.py +++ b/skimage/morphology/tests/test_misc.py @@ -1,10 +1,12 @@ import numpy as np -from numpy.testing import assert_array_equal, assert_equal +from numpy.testing import assert_array_equal, assert_equal, assert_raises from skimage.morphology import remove_small_objects test_image = np.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 1]], bool) + + def test_one_connectivity(): expected = np.array([[0, 0, 0, 0, 0], [1, 1, 1, 0, 0], @@ -12,19 +14,43 @@ def test_one_connectivity(): observed = remove_small_objects(test_image, min_size=6) assert_array_equal(observed, expected) + def test_two_connectivity(): expected = np.array([[0, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]], bool) - observed = remove_small_objects(test_image, min_size=7, - connectivity=2) + observed = remove_small_objects(test_image, min_size=7, connectivity=2) assert_array_equal(observed, expected) + def test_in_place(): - observed = remove_small_objects(test_image, min_size=6, - in_place=True) + observed = remove_small_objects(test_image, min_size=6, in_place=True) assert_equal(observed is test_image, True, "remove_small_objects in_place argument failed.") + +def test_labeled_image(): + labeled_image = np.array([[2, 2, 2, 0, 1], + [2, 2, 2, 0, 1], + [2, 0, 0, 0, 0], + [0, 0, 3, 3, 3]], dtype=int) + expected = np.array([[2, 2, 2, 0, 0], + [2, 2, 2, 0, 0], + [2, 0, 0, 0, 0], + [0, 0, 3, 3, 3]], dtype=int) + observed = remove_small_objects(labeled_image, min_size=3) + assert_array_equal(observed, expected) + + +def test_float_input(): + float_test = np.random.rand(5, 5) + assert_raises(TypeError, remove_small_objects, float_test) + + +def test_negative_input(): + negative_int = np.random.randint(-4, -1, size=(5, 5)) + assert_raises(ValueError, remove_small_objects, negative_int) + + if __name__ == "__main__": np.testing.run_module_suite() From 332469c6df8fcb0d3151b457a76abccb1c136c1b Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Mon, 4 Mar 2013 01:24:26 +1100 Subject: [PATCH 8/9] Fix missed rename in example --- doc/examples/applications/plot_coins_segmentation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/examples/applications/plot_coins_segmentation.py b/doc/examples/applications/plot_coins_segmentation.py index 943c57fb..0d1d8a34 100644 --- a/doc/examples/applications/plot_coins_segmentation.py +++ b/doc/examples/applications/plot_coins_segmentation.py @@ -91,7 +91,7 @@ Small spurious objects are easily removed by setting a minimum size for valid objects. """ from skimage import morphology -coins_cleaned = morphology.remove_small_connected_components(fill_coins, 21) +coins_cleaned = morphology.remove_small_objects(fill_coins, 21) plt.figure(figsize=(4, 3)) plt.imshow(coins_cleaned, cmap=plt.cm.gray, interpolation='nearest') From 3249faf308af182435b081e28210274179fdd81e Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Mon, 4 Mar 2013 16:54:29 +1100 Subject: [PATCH 9/9] Add specific error messages and exceptions --- skimage/morphology/misc.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/skimage/morphology/misc.py b/skimage/morphology/misc.py index 719fba5a..bb0ff687 100644 --- a/skimage/morphology/misc.py +++ b/skimage/morphology/misc.py @@ -51,7 +51,11 @@ def remove_small_objects(ar, min_size=64, connectivity=1, in_place=False): >>> d is a True """ - structuring_element = nd.generate_binary_structure(ar.ndim, connectivity) + errmsg = "Only numpy.ndarrays of bool or integer type are supported. " + if type(ar) != np.ndarray: + raise TypeError(errmsg + "Got a %s." % type(ar)) + elif ar.dtype != bool and not np.issubdtype(ar.dtype, np.integer): + raise TypeError(errmsg + "Got a numpy.ndarray of type %s" % ar.dtype) if in_place: out = ar else: @@ -59,10 +63,15 @@ def remove_small_objects(ar, min_size=64, connectivity=1, in_place=False): if min_size == 0: # shortcut for efficiency return out if out.dtype == bool: - ccs = nd.label(ar, structuring_element)[0] + selem = nd.generate_binary_structure(ar.ndim, connectivity) + ccs = nd.label(ar, selem)[0] else: ccs = out - component_sizes = np.bincount(ccs.ravel()) + try: + component_sizes = np.bincount(ccs.ravel()) + except ValueError: + raise ValueError("Negative value labels are not supported. Try " + "relabeling the input with `scipy.ndimage.label`.") too_small = component_sizes < min_size too_small_mask = too_small[ccs] out[too_small_mask] = 0