mirror of
https://github.com/wassname/scikit-image.git
synced 2026-07-13 17:45:20 +08:00
Add function to clear border in binary images
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user