From 6fc4e11b9a871756eb35f32ff899016af02d858f Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Fri, 8 May 2015 22:32:29 -0700 Subject: [PATCH] Add in-place operation --- skimage/segmentation/_clear_border.py | 9 +++++++-- .../segmentation/tests/test_clear_border.py | 20 +++++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/skimage/segmentation/_clear_border.py b/skimage/segmentation/_clear_border.py index 318f8790..bc972754 100644 --- a/skimage/segmentation/_clear_border.py +++ b/skimage/segmentation/_clear_border.py @@ -3,7 +3,7 @@ import numpy as np from ..measure import label -def clear_border(labels, buffer_size=0, bgval=0): +def clear_border(labels, buffer_size=0, bgval=0, in_place=False): """Clear objects connected to the label image border. The changes will be applied directly to the input. @@ -17,11 +17,13 @@ def clear_border(labels, buffer_size=0, bgval=0): that touch the outside of the image are removed. bgval : float or int, optional Cleared objects are set to this value. + in_place : bool, optional + Whether or not to manipulate the labels array in-place. Returns ------- labels : (N, M) array - Cleared binary image. Note that the input label image is modified. + Cleared binary image. Examples -------- @@ -69,6 +71,9 @@ def clear_border(labels, buffer_size=0, bgval=0): # create mask for pixels to clear mask = label_mask[labels.ravel()].reshape(labels.shape) + if not in_place: + image = image.copy() + # clear border pixels image[mask] = bgval diff --git a/skimage/segmentation/tests/test_clear_border.py b/skimage/segmentation/tests/test_clear_border.py index 51431260..b626ea2b 100644 --- a/skimage/segmentation/tests/test_clear_border.py +++ b/skimage/segmentation/tests/test_clear_border.py @@ -1,5 +1,5 @@ import numpy as np -from numpy.testing import assert_array_equal +from numpy.testing import assert_array_equal, assert_ from skimage.segmentation import clear_border @@ -34,14 +34,30 @@ def test_clear_border_non_binary(): [3, 4, 5, 4, 2], [3, 3, 2, 1, 2]]) - result = clear_border(image.copy()) + result = clear_border(image) expected = np.array([[0, 0, 0, 0, 0], [0, 0, 5, 4, 0], [0, 4, 5, 4, 0], [0, 0, 0, 0, 0]]) assert_array_equal(result, expected) + assert_(not np.all(image == result)) +def test_clear_border_non_binary_inplace(): + image = np.array([[1, 2, 3, 1, 2], + [3, 3, 5, 4, 2], + [3, 4, 5, 4, 2], + [3, 3, 2, 1, 2]]) + + result = clear_border(image, in_place=True) + expected = np.array([[0, 0, 0, 0, 0], + [0, 0, 5, 4, 0], + [0, 4, 5, 4, 0], + [0, 0, 0, 0, 0]]) + + assert_array_equal(result, expected) + assert_array_equal(image, result) + if __name__ == "__main__": np.testing.run_module_suite()