Skip to content

Add boundary_mode parameter to binary_blobs - #7909

Merged
stefanv merged 13 commits into
scikit-image:mainfrom
Tensorboy2:add-binary-blobs-mode
Nov 17, 2025
Merged

stefanv merged 13 commits into
scikit-image:mainfrom
Tensorboy2:add-binary-blobs-mode

Conversation

@Tensorboy2

@Tensorboy2 Tensorboy2 commented Sep 23, 2025 •

Copy link
Copy Markdown
Contributor

Description

binary_blobs now supports a mode parameter for the Gaussian filter, allowing periodic boundary conditions with mode="wrap".

Checklist

Update to _binary_blobs doc string:

def binary_blobs(
    length=512,
    blob_size_fraction=0.1,
    n_dim=2,
    volume_fraction=0.5,
    rng=None,
    mode='nearest',
):
"""
...
mode : str, default "nearest"
        The `mode` parameter passed to the Gaussian filter.
        Use "wrap" for periodic boundary conditions.
...
"""

Default remains the default of the Gaussian filter.

Addition to test_binary_blobs:

wrap_blobs = data.binary_blobs(length=64, mode="wrap")
assert wrap_blobs.shape == (64, 64)
assert wrap_blobs.dtype == bool

Release note

`binary_blobs` now supports a `mode` parameter for the Gaussian filter, allowing periodic boundary conditions with `mode="wrap"`.

@lagru

lagru commented Sep 23, 2025

Copy link
Copy Markdown
Member

Thanks for the suggestion. I'm not opposed to adding this parameter or something similar. Though, I'd like to understand why and how this parameter would be useful to you. :)

@Tensorboy2

Copy link
Copy Markdown
Contributor Author

Of course @lagru! I am using the binary blobs function in my research as it provides the structures I need. The domain I research requiers periodic boundary conditions and the 'wrap' mode provides this perfectly. Adding this to the function instead of implementing it seperatly cleans up my work and lets me more easily use the structures later :)

@lagru

lagru commented Sep 24, 2025

Copy link
Copy Markdown
Member

Ah, I was initially confused why a mode="wrap" might be useful. I thought, that's still a non-random effect on the boundary. But that mode actually allows concatenating the generated results. Can I be curious and ask what domain? :)

Comment thread src/skimage/data/_binary_blobs.py Resolved
Comment thread src/skimage/data/_binary_blobs.py Resolved
Comment thread tests/skimage/data/test_data.py Outdated
Comment on lines +133 to +135
wrap_blobs = data.binary_blobs(length=64, mode="wrap")
assert wrap_blobs.shape == (64, 64)
assert wrap_blobs.dtype == bool

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there some way to test the periodicity? As it is now, this does just test that the new parameter works and returns "some" boolean array...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are statistical ways to do this. I am not very familiar with how a methods statistics can be tested in a project like this?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can check, that the edge slices in each respective dimension are similar to each other within a given tolerance. For example, compare blobs[1, :] with blobs[-1, :]. 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. This tends to be true:

def is_periodic(arr, threshold=0.3):
    for axis in range(arr.ndim):
        first_slice = np.take(arr, 0, axis=axis)
        last_slice = np.take(arr, -1, axis=axis)
        mismatch = np.mean(first_slice != last_slice)
        if mismatch >= threshold:
            return False
    return True

However, I tested it for various modes in the gaussian and both "wrap" and "constant" return true, while "reflect" and "nearest" return false.


def binary_blobs(
length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, rng=None
length=512,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated, but such a missed opportunity to use shape as a parameter here. That would allow creating array with different lengths in each dimension.

Maybe something to change in skimage2? @scikit-image/core

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is very true! Shape would be cleaner.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, let's put this on the 2.0 list.

@Tensorboy2

Copy link
Copy Markdown
Contributor Author

Yes! I use the structures to study transport properties of 2d porous media. :)

@lagru

lagru commented Sep 26, 2025

Copy link
Copy Markdown
Member

To get a better feel for the effect of boundary_mode="wrap" I created this snippet and plot:

Details
import numpy as np
import matplotlib.pyplot as plt
import skimage as ski

blobs_nearest = ski.data.binary_blobs(300, rng=3, boundary_mode="nearest")
blobs_wrap = ski.data.binary_blobs(300, rng=3, boundary_mode="wrap")

concat_nearest = np.concatenate([blobs_nearest, blobs_nearest * 2], axis=1)
concat_wrap = np.concatenate([blobs_wrap, blobs_wrap * 2], axis=1)
concat_diff = np.abs(concat_wrap - concat_nearest)

plt.close()
fig, ax = plt.subplots(1, 3)
ax[0].set_title("Nearest")
ax[0].imshow(concat_nearest.T)
ax[1].set_title("Wrap")
ax[1].imshow(concat_wrap.T)
ax[2].set_title("Diff")
ax[2].imshow(concat_diff.T)
fig.tight_layout()
plt.show()
binary_blobs_nearest_vs_wraps

One can nicely see, the effect at the edge. I think the differences inside the image are because the function has to account for the differences at the edge to keep the desired volume_fraction.

I found it a bit tricky to describe the boundary modes in terms of their
effects on the resulting blobs. It's tempting to delegate to the
docstring of `gaussian` but that isn't really helpful to users without
being aware of the actual algorithm or implementation.

I opted to not support all modes that gaussian supports. I'm not sure
how useful they would really be in addition to 'nearest' and 'wrap'.

If I could switch defaults, I would probably switch to 'wrap' or
'constant' over 'nearest'. 'nearest' has a significant effect but only
for blobs whose center lies exactly on the edge.

@lagru lagru left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Tensorboy2 I took the liberty to push a few new suggestions. Their commit message(s) add more context on the why. I'd be curious what you think about the current state and if you agree with only supporting the existing default and the new 'wrap' mode.

Feel totally welcome to add to this, revert or ask for clarification!

If the CI stays green and you are happy to, I think this is ready to merge.

@Tensorboy2

Copy link
Copy Markdown
Contributor Author

I very much agree with limiting the modes. My choice of default would be "wrap", but keeping the gaussian default is probably best for clarity.

@lagru
lagru requested a review from stefanv September 27, 2025 16:47
@lagru lagru changed the title added mode to binary blobs that go into gaussian Add boundary_mode parameter to binary_blobs Sep 29, 2025

@stefanv stefanv left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about the clamping; the rest looks good to me.


def binary_blobs(
length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, rng=None
length=512,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, let's put this on the 2.0 list.

Comment thread src/skimage/data/_binary_blobs.py Resolved
Comment thread src/skimage/data/_binary_blobs.py Resolved
Comment thread src/skimage/data/_binary_blobs.py Resolved
Comment thread src/skimage/data/_binary_blobs.py Resolved
Comment thread src/skimage/data/_binary_blobs.py Resolved
Comment thread src/skimage/data/_binary_blobs.py Resolved
raise ValueError(f"unsupported `boundary_mode`: {boundary_mode!r}")

blob_size = blob_size_fraction * length
if blob_size < 0.1:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This clamping feels a bit magical; why not just limit the blob size fraction to somewhere between 0.1 and 1?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For small blob_size_fraction it will try to allocate an array of size (n_dim, int(1.0 / blob_size_fraction) ** n_dim). This can lead to unexpectedly large arrays being allocated.

I chose blob_size_fraction * length < 0.1 as a cut-off because its results is very probably unexpected. At that point the returned array will mostly consist of 1s everywhere because almost every pixel has been marked as a seed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But maybe I shouldn't call this blob_size as the actual size of blobs is influenced by volume_fraction too.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe something like blob_pixel_ratio?

@lagru
lagru requested a review from stefanv October 30, 2025 12:17

@stefanv stefanv left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Discussed on weekly call: we probably want to get this in without the clipping, but Lars will do one more scan to ensure this wasn't done to avoid high memory use.
  • Check that shape issue has been captured around

Comment on lines +86 to +87
f"Clamping to `blob_size_fraction={clamped_size_fraction}` and a blob size "
f"of {clamped_blob_size} pixels to avoid allocating excessive memory.",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stefanv, avoiding the allocation of excessive memory was indeed the reason for the clamping.

@stefanv
stefanv merged commit fb60f1b into scikit-image:main Nov 17, 2025
@stefanv

stefanv commented Nov 17, 2025

Copy link
Copy Markdown
Member

Thanks for your contribution, @Tensorboy2!

@stefanv stefanv added this to the 0.26 milestone Nov 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants