Add function to clear border in binary images

This commit is contained in:
Johannes Schönberger
2012-08-16 22:35:04 +02:00
parent 571151958f
commit bb51f62f93
2 changed files with 68 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
import numpy as np
from skimage.measure import regionprops
from skimage.morphology import label
def clear_border(image, buffer_size=0, bgval=0):
"""Clear objects connected to image border.
The changes will be applied to the input image.
Parameters
----------
image : (N, M) array
binary image
buffer_size : int, optional
define additional buffer around image border
bgval : float or int, optional
value for cleared objects
Returns
-------
image : (N, M) array
cleared binary image
"""
rows, cols = image.shape
for prop in regionprops(label(image), ['BoundingBox', 'Image']):
minr, minc, maxr, maxc = prop['BoundingBox']
if (
minr <= buffer_size
or minc <= buffer_size
or maxr >= rows - buffer_size
or maxc >= cols - buffer_size
):
r, c = np.nonzero(prop['Image'])
image[minr + r, minc + c] = bgval
return image
@@ -0,0 +1,32 @@
import numpy as np
from numpy.testing import assert_array_equal, assert_equal
from skimage.morphology import clear_border
def test_possible_hull():
image = np.array(
[[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]])
# test default case
result = clear_border(image.copy())
ref = image.copy()
ref[2, 0] = 0
ref[0, -2] = 0
assert_array_equal(result, ref)
# test buffer
result = clear_border(image.copy(), 1)
assert_array_equal(result, np.zeros(result.shape))
# test background value
result = clear_border(image.copy(), 1, 2)
assert_array_equal(result, 2 * image)
if __name__ == "__main__":
np.testing.run_module_suite()