bioimage_py.filters

Block-wise image filters.

 1"""Block-wise image filters."""
 2from .filters import (
 3    apply_filter,
 4    gaussian_gradient_magnitude,
 5    gaussian_smoothing,
 6    laplacian_of_gaussian,
 7)
 8
 9__all__ = [
10    "apply_filter",
11    "gaussian_smoothing",
12    "gaussian_gradient_magnitude",
13    "laplacian_of_gaussian",
14]
def apply_filter( input: 'SourceLike', filter_name: str, sigma: Union[float, Sequence[float]], output: 'Optional[SourceLike]' = None, *, outer_scale: Optional[float] = None, return_channel: Optional[int] = None, block_shape: Optional[Tuple[int, ...]] = None, job_type: str = 'local', job_config: Optional[bioimage_py.runner.RunnerConfig] = None, num_workers: int = 1, mask: 'Optional[SourceLike]' = None, block_ids: Optional[Sequence[int]] = None, resume_from: Optional[str] = None) -> 'SourceLike':
116def apply_filter(
117    input: SourceLike,
118    filter_name: str,
119    sigma: Sigma,
120    output: Optional[SourceLike] = None,
121    *,
122    outer_scale: Optional[float] = None,
123    return_channel: Optional[int] = None,
124    block_shape: Optional[Tuple[int, ...]] = None,
125    job_type: str = "local",
126    job_config: Optional[RunnerConfig] = None,
127    num_workers: int = 1,
128    mask: Optional[SourceLike] = None,
129    block_ids: Optional[Sequence[int]] = None,
130    resume_from: Optional[str] = None,
131) -> SourceLike:
132    """Apply a (gaussian-family) filter block-wise.
133
134    Args:
135        input: The input data (a numpy/zarr/n5 array or a `Source`).
136        filter_name: The filter to apply: one of ``"gaussian_smoothing"``,
137            ``"gaussian_gradient_magnitude"``, ``"laplacian_of_gaussian"``,
138            ``"hessian_of_gaussian_eigenvalues"`` or ``"structure_tensor_eigenvalues"``.
139        sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence
140            of floats (anisotropic).
141        output: The output array to write into. Optional for local execution — a numpy array
142            is allocated and returned if omitted; **required** for distributed execution. For a
143            multi-channel response the output has a leading channel axis of shape ``(ndim, ...)``.
144        outer_scale: Outer scale, required for ``structure_tensor_eigenvalues``.
145        return_channel: For multi-channel filters, select a single channel (scalar output).
146        block_shape: Shape of the processing blocks. Defaults to the input chunk shape;
147            required for unchunked data.
148        job_type: Execution backend: one of ``"local"``, ``"subprocess"`` or ``"slurm"``.
149        job_config: Backend configuration (a `RunnerConfig` / `SlurmConfig`).
150        num_workers: Number of parallel workers (threads for ``local``, tasks for distributed
151            backends).
152        mask: Optional binary mask; values outside the mask are excluded from the computation
153            (out-of-mask output voxels are left unchanged).
154        block_ids: Restrict processing to these block ids (e.g. to re-run previously failed blocks
155            into the existing ``output``). Mutually exclusive with ``resume_from``.
156        resume_from: Distributed only; the preserved temp folder of a failed run to resume (see
157            ``runner.run``); the missing blocks are written into ``output``. Mutually exclusive
158            with ``block_ids``.
159
160    Returns:
161        The output array (the provided ``output``, or a newly allocated numpy array).
162    """
163    if filter_name not in _FILTER_FUNCTIONS:
164        raise ValueError(f"Unknown filter {filter_name!r}; valid filters: {sorted(_FILTER_FUNCTIONS)}.")
165    if filter_name == "structure_tensor_eigenvalues" and outer_scale is None:
166        raise ValueError("structure_tensor_eigenvalues requires 'outer_scale'.")
167    check_rerun_args(job_type, resume_from, block_ids)
168
169    src = as_source(input)
170    ndim = src.ndim
171    order = _ORDERS[filter_name]
172    extra_args: Tuple[float, ...] = (
173        (float(outer_scale),) if filter_name == "structure_tensor_eigenvalues" else ()
174    )
175    multi_channel = filter_name in _MULTI_CHANNEL and return_channel is None
176    # A subset/resume rerun is inherently block-wise, so it cannot use the direct (whole-array) path.
177    direct = (is_direct(job_type, num_workers, block_shape) and mask is None
178              and block_ids is None and resume_from is None)
179
180    if output is None:
181        if job_type != "local":
182            raise ValueError(
183                f"'output' is required for distributed execution (job_type={job_type!r}); "
184                "pass a file-backed (zarr/n5) output array."
185            )
186        out_array: SourceLike = _allocate_output(src, ndim, multi_channel)
187    else:
188        out_array = output
189
190    out = as_source(out_array)
191    if not direct and _same_array(out, src):
192        raise ValueError("Block-wise filtering needs 'output' to differ from 'input'.")
193
194    if direct:
195        _apply_direct(src, out, filter_name, sigma, extra_args, ndim, return_channel)
196        return out_array
197
198    compute = _make_compute(filter_name, sigma, extra_args, ndim, return_channel)
199    halo = normalize_halo(sigma_to_halo(sigma, order), ndim)
200    runner = get_runner(job_type, job_config)
201    runner.run(compute, [input], outputs=[out], halo=halo, block_shape=block_shape,
202               mask=mask, num_workers=num_workers, block_ids=block_ids, resume_from=resume_from,
203               name=filter_name)
204    return out_array

Apply a (gaussian-family) filter block-wise.

Args: input: The input data (a numpy/zarr/n5 array or a Source). filter_name: The filter to apply: one of "gaussian_smoothing", "gaussian_gradient_magnitude", "laplacian_of_gaussian", "hessian_of_gaussian_eigenvalues" or "structure_tensor_eigenvalues". sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence of floats (anisotropic). output: The output array to write into. Optional for local execution — a numpy array is allocated and returned if omitted; required for distributed execution. For a multi-channel response the output has a leading channel axis of shape (ndim, ...). outer_scale: Outer scale, required for structure_tensor_eigenvalues. return_channel: For multi-channel filters, select a single channel (scalar output). block_shape: Shape of the processing blocks. Defaults to the input chunk shape; required for unchunked data. job_type: Execution backend: one of "local", "subprocess" or "slurm". job_config: Backend configuration (a RunnerConfig / SlurmConfig). num_workers: Number of parallel workers (threads for local, tasks for distributed backends). mask: Optional binary mask; values outside the mask are excluded from the computation (out-of-mask output voxels are left unchanged). block_ids: Restrict processing to these block ids (e.g. to re-run previously failed blocks into the existing output). Mutually exclusive with resume_from. resume_from: Distributed only; the preserved temp folder of a failed run to resume (see runner.run); the missing blocks are written into output. Mutually exclusive with block_ids.

Returns: The output array (the provided output, or a newly allocated numpy array).

def gaussian_smoothing( input: 'SourceLike', sigma: Union[float, Sequence[float]], output: 'Optional[SourceLike]' = None, **kwargs) -> 'SourceLike':
207def gaussian_smoothing(input: SourceLike, sigma: Sigma, output: Optional[SourceLike] = None,
208                       **kwargs) -> SourceLike:
209    """Gaussian smoothing, block-wise.
210
211    Args:
212        input: The input data (a numpy/zarr/n5 array or a `Source`).
213        sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence
214            of floats (anisotropic).
215        output: The output array to write into. Optional for local execution — a numpy array
216            is allocated and returned if omitted; **required** for distributed execution.
217        **kwargs: Additional keyword arguments forwarded to :func:`apply_filter` (``block_shape``,
218            ``job_type``, ``job_config``, ``num_workers``, ``mask``, ``block_ids``, ``resume_from``).
219
220    Returns:
221        The output array (the provided ``output``, or a newly allocated numpy array).
222    """
223    return apply_filter(input, "gaussian_smoothing", sigma, output, **kwargs)

Gaussian smoothing, block-wise.

Args: input: The input data (a numpy/zarr/n5 array or a Source). sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence of floats (anisotropic). output: The output array to write into. Optional for local execution — a numpy array is allocated and returned if omitted; required for distributed execution. **kwargs: Additional keyword arguments forwarded to apply_filter() (block_shape, job_type, job_config, num_workers, mask, block_ids, resume_from).

Returns: The output array (the provided output, or a newly allocated numpy array).

def gaussian_gradient_magnitude( input: 'SourceLike', sigma: Union[float, Sequence[float]], output: 'Optional[SourceLike]' = None, **kwargs) -> 'SourceLike':
226def gaussian_gradient_magnitude(input: SourceLike, sigma: Sigma,
227                                output: Optional[SourceLike] = None, **kwargs) -> SourceLike:
228    """Gaussian gradient magnitude, block-wise.
229
230    Args:
231        input: The input data (a numpy/zarr/n5 array or a `Source`).
232        sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence
233            of floats (anisotropic).
234        output: The output array to write into. Optional for local execution — a numpy array
235            is allocated and returned if omitted; **required** for distributed execution.
236        **kwargs: Additional keyword arguments forwarded to :func:`apply_filter` (``block_shape``,
237            ``job_type``, ``job_config``, ``num_workers``, ``mask``, ``block_ids``, ``resume_from``).
238
239    Returns:
240        The output array (the provided ``output``, or a newly allocated numpy array).
241    """
242    return apply_filter(input, "gaussian_gradient_magnitude", sigma, output, **kwargs)

Gaussian gradient magnitude, block-wise.

Args: input: The input data (a numpy/zarr/n5 array or a Source). sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence of floats (anisotropic). output: The output array to write into. Optional for local execution — a numpy array is allocated and returned if omitted; required for distributed execution. **kwargs: Additional keyword arguments forwarded to apply_filter() (block_shape, job_type, job_config, num_workers, mask, block_ids, resume_from).

Returns: The output array (the provided output, or a newly allocated numpy array).

def laplacian_of_gaussian( input: 'SourceLike', sigma: Union[float, Sequence[float]], output: 'Optional[SourceLike]' = None, **kwargs) -> 'SourceLike':
245def laplacian_of_gaussian(input: SourceLike, sigma: Sigma, output: Optional[SourceLike] = None,
246                          **kwargs) -> SourceLike:
247    """Laplacian of Gaussian, block-wise.
248
249    Args:
250        input: The input data (a numpy/zarr/n5 array or a `Source`).
251        sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence
252            of floats (anisotropic).
253        output: The output array to write into. Optional for local execution — a numpy array
254            is allocated and returned if omitted; **required** for distributed execution.
255        **kwargs: Additional keyword arguments forwarded to :func:`apply_filter` (``block_shape``,
256            ``job_type``, ``job_config``, ``num_workers``, ``mask``, ``block_ids``, ``resume_from``).
257
258    Returns:
259        The output array (the provided ``output``, or a newly allocated numpy array).
260    """
261    return apply_filter(input, "laplacian_of_gaussian", sigma, output, **kwargs)

Laplacian of Gaussian, block-wise.

Args: input: The input data (a numpy/zarr/n5 array or a Source). sigma: The filter standard deviation: a scalar (isotropic) or a per-axis sequence of floats (anisotropic). output: The output array to write into. Optional for local execution — a numpy array is allocated and returned if omitted; required for distributed execution. **kwargs: Additional keyword arguments forwarded to apply_filter() (block_shape, job_type, job_config, num_workers, mask, block_ids, resume_from).

Returns: The output array (the provided output, or a newly allocated numpy array).