scikit-image
61 строка · 2.1 Кб
1import numpy as np
2
3from .._shared.filters import gaussian
4
5
6def binary_blobs(
7length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, rng=None
8):
9"""
10Generate synthetic binary image with several rounded blob-like objects.
11
12Parameters
13----------
14length : int, optional
15Linear size of output image.
16blob_size_fraction : float, optional
17Typical linear size of blob, as a fraction of ``length``, should be
18smaller than 1.
19n_dim : int, optional
20Number of dimensions of output image.
21volume_fraction : float, default 0.5
22Fraction of image pixels covered by the blobs (where the output is 1).
23Should be in [0, 1].
24rng : {`numpy.random.Generator`, int}, optional
25Pseudo-random number generator.
26By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
27If `rng` is an int, it is used to seed the generator.
28
29Returns
30-------
31blobs : ndarray of bools
32Output binary image
33
34Examples
35--------
36>>> from skimage import data
37>>> data.binary_blobs(length=5, blob_size_fraction=0.2) # doctest: +SKIP
38array([[ True, False, True, True, True],
39[ True, True, True, False, True],
40[False, True, False, True, True],
41[ True, False, False, True, True],
42[ True, False, False, False, True]])
43>>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.1)
44>>> # Finer structures
45>>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.05)
46>>> # Blobs cover a smaller volume fraction of the image
47>>> blobs = data.binary_blobs(length=256, volume_fraction=0.3)
48
49"""
50
51rs = np.random.default_rng(rng)
52shape = tuple([length] * n_dim)
53mask = np.zeros(shape)
54n_pts = max(int(1.0 / blob_size_fraction) ** n_dim, 1)
55points = (length * rs.random((n_dim, n_pts))).astype(int)
56mask[tuple(indices for indices in points)] = 1
57mask = gaussian(
58mask, sigma=0.25 * length * blob_size_fraction, preserve_range=False
59)
60threshold = np.percentile(mask, 100 * (1 - volume_fraction))
61return np.logical_not(mask < threshold)
62