File size: 18,671 Bytes
d381118 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 | """Miscellaneous morphology functions."""
import numpy as np
import functools
import warnings
from scipy import ndimage as ndi
from scipy.spatial import cKDTree
from .._shared.utils import warn, deprecate_parameter, DEPRECATED
from ._misc_cy import _remove_objects_by_distance
# Our function names don't exactly correspond to ndimages.
# This dictionary translates from our names to scipy's.
funcs = ('erosion', 'dilation', 'opening', 'closing')
skimage2ndimage = {x: 'grey_' + x for x in funcs}
# These function names are the same in ndimage.
funcs = (
'black_tophat',
'white_tophat',
)
skimage2ndimage.update({x: x for x in funcs})
def default_footprint(func):
"""Decorator to add a default footprint to morphology functions.
Parameters
----------
func : function
A morphology function such as erosion, dilation, opening, closing,
white_tophat, or black_tophat.
Returns
-------
func_out : function
The function, using a default footprint of same dimension
as the input image with connectivity 1.
"""
@functools.wraps(func)
def func_out(image, footprint=None, *args, **kwargs):
if footprint is None:
footprint = ndi.generate_binary_structure(image.ndim, 1)
return func(image, footprint=footprint, *args, **kwargs)
return func_out
def _check_dtype_supported(ar):
# Should use `issubdtype` for bool below, but there's a bug in numpy 1.7
if not (ar.dtype == bool or np.issubdtype(ar.dtype, np.integer)):
raise TypeError(
"Only bool or integer image types are supported. " f"Got {ar.dtype}."
)
@deprecate_parameter(
deprecated_name="min_size",
new_name="max_size",
start_version="0.26.0",
stop_version="2.0.0",
template=f"{deprecate_parameter.replace_parameter_template} "
"Note that the new threshold removes objects smaller than **or equal to** "
"its value, while the previous parameter only removed smaller ones.",
)
def remove_small_objects(
ar, min_size=DEPRECATED, connectivity=1, *, max_size=64, out=None
):
"""Remove objects smaller than the specified size.
Expects `ar` to be an array with labeled objects, and removes objects
smaller than or equal to `max_size`. If `ar` is bool, the image is first
labeled. This leads to potentially different behavior for bool vs. 0-and-1
arrays.
Parameters
----------
ar : ndarray (arbitrary shape, int or bool type)
The array containing the objects of interest. If the array type is
int, the ints must be non-negative.
max_size : int, optional (default: 64)
Remove objects whose contiguous area (or volume, in N-D) contains this
number of pixels or fewer.
.. versionadded:: 0.26
To make the naming clearer, replaces deprecated `min_size`
which only removed objects strictly smaller than its size.
connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)
The connectivity defining the neighborhood of a pixel. Used during
labelling if `ar` is bool.
out : ndarray
Array of the same shape as `ar`, into which the output is
placed. By default, a new array is created.
Raises
------
TypeError
If the input array is of an invalid type, such as float or string.
ValueError
If the input array contains negative values.
Returns
-------
out : ndarray, same shape and type as input `ar`
The input array with small connected components removed.
See Also
--------
skimage.morphology.remove_small_holes
skimage.morphology.remove_objects_by_distance
Examples
--------
>>> from skimage import morphology
>>> a = np.array([[0, 0, 0, 1, 0],
... [1, 1, 1, 0, 0],
... [1, 1, 1, 0, 1]], bool)
>>> b = morphology.remove_small_objects(a, max_size=5)
>>> b
array([[False, False, False, False, False],
[ True, True, True, False, False],
[ True, True, True, False, False]])
>>> c = morphology.remove_small_objects(a, max_size=6, connectivity=2)
>>> c
array([[False, False, False, True, False],
[ True, True, True, False, False],
[ True, True, True, False, False]])
>>> d = morphology.remove_small_objects(a, max_size=5, out=a)
>>> d is a
True
"""
# Raising type error if not int or bool
_check_dtype_supported(ar)
if out is None:
out = ar.copy()
else:
out[:] = ar
if max_size == 0: # shortcut for efficiency
return out
if out.dtype == bool:
footprint = ndi.generate_binary_structure(ar.ndim, connectivity)
ccs = np.zeros_like(ar, dtype=np.int32)
ndi.label(ar, footprint, output=ccs)
else:
ccs = out
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` or "
"`skimage.morphology.label`."
)
if len(component_sizes) == 2 and out.dtype != bool:
warn(
"Only one label was provided to `remove_small_objects`. "
"Did you mean to use a boolean array?"
)
if min_size is not DEPRECATED:
# Exclusive threshold is deprecated behavior
too_small = component_sizes < min_size
else:
# New behavior uses inclusive threshold
too_small = component_sizes <= max_size
too_small_mask = too_small[ccs]
out[too_small_mask] = 0
return out
@deprecate_parameter(
deprecated_name="area_threshold",
new_name="max_size",
start_version="0.26.0",
stop_version="2.0.0",
template=f"{deprecate_parameter.replace_parameter_template} "
"Note that the new threshold removes objects smaller than **or equal to** "
"its value, while the previous parameter only removed smaller ones.",
)
def remove_small_holes(
ar, area_threshold=DEPRECATED, connectivity=1, *, max_size=64, out=None
):
"""Remove contiguous holes smaller than the specified size.
Parameters
----------
ar : ndarray (arbitrary shape, int or bool type)
The array containing the connected components of interest.
max_size : int, optional (default: 64)
Remove holes whose contiguous area (or volume, in N-D) contains this
number of pixels or fewer.
.. versionadded:: 0.26
To make the naming clearer, replaces deprecated `area_threshold`
which only removed holes strictly smaller than its size.
connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)
The connectivity defining the neighborhood of a pixel.
out : ndarray
Array of the same shape as `ar` and bool dtype, into which the
output is placed. By default, a new array is created.
Raises
------
TypeError
If the input array is of an invalid type, such as float or string.
ValueError
If the input array contains negative values.
Returns
-------
out : ndarray, same shape and type as input `ar`
The input array with small holes within connected components removed.
See Also
--------
skimage.morphology.remove_small_objects
skimage.morphology.remove_objects_by_distance
Examples
--------
>>> from skimage import morphology
>>> a = np.array([[1, 1, 1, 1, 1, 0],
... [1, 1, 1, 0, 1, 0],
... [1, 0, 0, 1, 1, 0],
... [1, 1, 1, 1, 1, 0]], bool)
>>> b = morphology.remove_small_holes(a, max_size=1)
>>> b
array([[ True, True, True, True, True, False],
[ True, True, True, True, True, False],
[ True, False, False, True, True, False],
[ True, True, True, True, True, False]])
>>> c = morphology.remove_small_holes(a, max_size=1, connectivity=2)
>>> c
array([[ True, True, True, True, True, False],
[ True, True, True, False, True, False],
[ True, False, False, True, True, False],
[ True, True, True, True, True, False]])
>>> d = morphology.remove_small_holes(a, max_size=1, out=a)
>>> d is a
True
Notes
-----
If the array type is int, it is assumed that it contains already-labeled
objects. The labels are not kept in the output image (this function always
outputs a bool image). It is suggested that labeling is completed after
using this function.
"""
_check_dtype_supported(ar)
# Creates warning if image is an integer image
if ar.dtype != bool:
warn(
"Any labeled images will be returned as a boolean array. "
"Did you mean to use a boolean array?",
UserWarning,
)
if out is not None:
if out.dtype != bool:
raise TypeError("out dtype must be bool")
else:
out = ar.astype(bool, copy=True)
# Creating the inverse of ar
np.logical_not(ar, out=out)
# removing small objects from the inverse of ar
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="Parameter `min_size` is deprecated",
category=FutureWarning,
)
out = remove_small_objects(
out,
min_size=area_threshold,
max_size=max_size,
connectivity=connectivity,
out=out,
)
np.logical_not(out, out=out)
return out
def remove_objects_by_distance(
label_image,
min_distance,
*,
priority=None,
p_norm=2,
spacing=None,
out=None,
):
"""Remove objects, in specified order, until remaining are a minimum distance apart.
Remove labeled objects from an image until the remaining ones are spaced
more than a given distance from one another. By default, smaller objects
are removed first.
Parameters
----------
label_image : ndarray of integers
An n-dimensional array containing object labels, e.g. as returned by
:func:`~.label`. A value of zero is considered background, all other
object IDs must be positive integers.
min_distance : int or float
Remove objects whose distance to other objects is not greater than this
positive value. Objects with a lower `priority` are removed first.
priority : ndarray, optional
Defines the priority with which objects are removed. Expects a
1-dimensional array of length
:func:`np.amax(label_image) + 1 <numpy.amax>` that contains the priority
for each object's label at the respective index. Objects with a lower value
are removed first until all remaining objects fulfill the distance
requirement. If not given, priority is given to objects with a higher
number of samples and their label value second.
p_norm : int or float, optional
The Minkowski distance of order p, used to calculate the distance
between objects. The default ``2`` corresponds to the Euclidean
distance, ``1`` to the "Manhattan" distance, and ``np.inf`` to the
Chebyshev distance.
spacing : sequence of float, optional
The pixel spacing along each axis of `label_image`. If not specified,
a grid spacing of unity (1) is implied.
out : ndarray, optional
Array of the same shape and dtype as `image`, into which the output is
placed. By default, a new array is created.
Returns
-------
out : ndarray
Array of the same shape as `label_image`, for which objects that violate
the `min_distance` condition were removed.
See Also
--------
skimage.morphology.remove_small_objects
Remove objects smaller than the specified size.
skimage.morphology.remove_small_holes
Remove holes smaller than the specified size.
Notes
-----
The basic steps of this algorithm work as follows:
1. Find the indices for of all given objects and separate them depending on
if they point to an object's border or not.
2. Sort indices by their label value, ensuring that indices which point to
the same object are next to each other. This optimization allows finding
all parts of an object, simply by stepping to the neighboring indices.
3. Sort boundary indices by `priority`. Use a stable-sort to preserve the
ordering from the previous sorting step. If `priority` is not given,
use :func:`numpy.bincount` as a fallback.
4. Construct a :class:`scipy.spatial.cKDTree` from the boundary indices.
5. Iterate across boundary indices in priority-sorted order, and query the
kd-tree for objects that are too close. Remove ones that are and don't
take them into account when evaluating other objects later on.
The performance of this algorithm depends on the number of samples in
`label_image` that belong to an object's border.
Examples
--------
>>> import skimage as ski
>>> ski.morphology.remove_objects_by_distance(np.array([2, 0, 1, 1]), 2)
array([0, 0, 1, 1])
>>> ski.morphology.remove_objects_by_distance(
... np.array([2, 0, 1, 1]), 2, priority=np.array([0, 1, 9])
... )
array([2, 0, 0, 0])
>>> label_image = np.array(
... [[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
... [8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9],
... [0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
... [0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0],
... [2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]]
... )
>>> ski.morphology.remove_objects_by_distance(
... label_image, min_distance=3
... )
array([[8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
[8, 8, 8, 0, 0, 0, 0, 0, 0, 9, 9],
[0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7]])
"""
if min_distance < 0:
raise ValueError(f"min_distance must be >= 0, was {min_distance}")
if not np.issubdtype(label_image.dtype, np.integer):
raise ValueError(
f"`label_image` must be of integer dtype, got {label_image.dtype}"
)
if out is None:
out = label_image.copy(order="C")
elif out is not label_image:
out[:] = label_image
# May create a copy if order is not C, account for that later
out_raveled = out.ravel(order="C")
if spacing is not None:
spacing = np.array(spacing)
if spacing.shape != (out.ndim,) or spacing.min() <= 0:
raise ValueError(
"`spacing` must contain exactly one positive factor "
"for each dimension of `label_image`"
)
indices = np.flatnonzero(out_raveled)
# Optimization: Split indices into those on the object boundaries and inner
# ones. The KDTree is built only from the boundary indices, which reduces
# the size of the critical loop significantly! Remaining indices are only
# used to remove the inner parts of objects as well.
if (spacing is None or np.all(spacing[0] == spacing)) and p_norm <= 2:
# For unity spacing we can make the borders more sparse by using a
# lower connectivity
footprint = ndi.generate_binary_structure(out.ndim, 1)
else:
footprint = ndi.generate_binary_structure(out.ndim, out.ndim)
border = (
ndi.maximum_filter(out, footprint=footprint)
!= ndi.minimum_filter(out, footprint=footprint)
).ravel()[indices]
border_indices = indices[border]
inner_indices = indices[~border]
if border_indices.size == 0:
# Image without any or only one object, return early
return out
# Sort by label ID first, so that IDs of the same object are contiguous
# in the sorted index. This allows fast discovery of the whole object by
# simple iteration up or down the index!
border_indices = border_indices[np.argsort(out_raveled[border_indices])]
inner_indices = inner_indices[np.argsort(out_raveled[inner_indices])]
if priority is None:
if not np.can_cast(out.dtype, np.intp, casting="safe"):
# bincount expects intp (32-bit) on WASM or i386, so down-cast to that
priority = np.bincount(out_raveled.astype(np.intp, copy=False))
else:
priority = np.bincount(out_raveled)
# `priority` can only be indexed by positive object IDs,
# `border_indices` contains all unique sorted IDs so check the lowest / first
smallest_id = out_raveled[border_indices[0]]
if smallest_id < 0:
raise ValueError(f"found object with negative ID {smallest_id!r}")
try:
# Sort by priority second using a stable sort to preserve the contiguous
# sorting of objects. Because each pixel in an object has the same
# priority we don't need to worry about separating objects.
border_indices = border_indices[
np.argsort(priority[out_raveled[border_indices]], kind="stable")[::-1]
]
except IndexError as error:
# Use np.amax only for the exception path to provide a nicer error message
expected_shape = (np.amax(out_raveled) + 1,)
if priority.shape != expected_shape:
raise ValueError(
"shape of `priority` must be (np.amax(label_image) + 1,), "
f"expected {expected_shape}, got {priority.shape} instead"
) from error
else:
raise
# Construct kd-tree from unraveled border indices (optionally scale by `spacing`)
unraveled_indices = np.unravel_index(border_indices, out.shape)
if spacing is not None:
unraveled_indices = tuple(
unraveled_indices[dim] * spacing[dim] for dim in range(out.ndim)
)
kdtree = cKDTree(data=np.asarray(unraveled_indices, dtype=np.float64).T)
_remove_objects_by_distance(
out=out_raveled,
border_indices=border_indices,
inner_indices=inner_indices,
kdtree=kdtree,
min_distance=min_distance,
p_norm=p_norm,
shape=label_image.shape,
)
if out_raveled.base is not out:
# `out_raveled` is a copy, re-assign
out[:] = out_raveled.reshape(out.shape)
return out
|