Skip to content

webknossos.dataset.view

View

View(path_to_mag_view: LazyPath, bounding_box: Optional[NDBoundingBox], mag: Mag, data_format: DataFormat, read_only: bool = False)

A View represents a bounding box to a region of a specific StorageBackend with additional functionality.

The View class provides a way to access and manipulate a specific region of data within a dataset. Write operations are restricted to the defined bounding box. Views are designed to be easily passed around as parameters and can be used to efficiently work with subsets of larger datasets.

Examples:

from webknossos.dataset import Dataset, View
dataset = Dataset.open("path/to/dataset")

# Get a view for a specific layer at mag 1
layer = dataset.get_layer("color")
view = layer.get_mag("1").get_view(size=(100, 100, 10))

# Read data from the view
data = view.read()

# Write data to the view (if not read_only)
import numpy as np
view.write(np.zeros(view.bounding_box.in_mag(view.mag).size))

Initialize a View instance for accessing and manipulating dataset regions.

Note: Do not use this constructor manually. Instead use View.get_view() (also available on a MagView) to get a View.

Parameters:

  • path_to_mag_view (Path) –

    Path to the magnification view directory.

  • array_info (ArrayInfo) –

    Information about the array structure and properties.

  • bounding_box (Optional[NDBoundingBox]) –

    The bounding box in mag 1 absolute coordinates. Optional only for mag_view since it overwrites the bounding_box property.

  • mag (Mag) –

    Magnification level of the view.

  • read_only (bool, default: False ) –

    Whether the view is read-only. Defaults to False.

Examples:

# The recommended way to create a View is through get_view():
layer = dataset.get_layer("color")
mag_view = layer.get_mag("1")
view = mag_view.get_view(size=(100, 100, 10))

bounding_box property

bounding_box: NDBoundingBox

Gets the bounding box of this view.

The bounding box defines the region of interest within the dataset in absolute coordinates at magnification level 1. It specifies both the position and size of the view's data.

Returns:

  • NDBoundingBox ( NDBoundingBox ) –

    A bounding box object representing the view's boundaries in absolute coordinates at magnification level 1.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))
bbox = view.bounding_box
print(f"Top-left corner: {bbox.topleft}")
print(f"Size: {bbox.size}")

global_offset property

global_offset: VecInt

⚠️ Deprecated, use view.bounding_box.in_mag(view.mag).topleft instead.

header property

header: Header

⚠️ Deprecated, use info instead.

info property

info: ArrayInfo

Get information about the array structure and properties.

Returns:

  • ArrayInfo ( ArrayInfo ) –

    Object containing array metadata such as data type, num_channels, and other array-specific information.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))
array_info = view.info
print(f"Data type: {array_info.data_type}")
print(f"Num channels: {array_info.num_channels}")

mag property

mag: Mag

Gets the magnification level of this view.

The magnification level determines the resolution at which the data is accessed. A higher magnification number means lower resolution (e.g., mag 2 means every second voxel, mag 4 means every fourth voxel, etc.).

Returns:

  • Mag ( Mag ) –

    The magnification level of this view.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))
print(f"Current magnification: {view.mag}")

read_only property

read_only: bool

Indicates whether this view is read-only.

When a view is read-only, write operations are not permitted. This property helps prevent accidental modifications to the dataset.

Returns:

  • bool ( bool ) –

    True if the view is read-only, False if write operations are allowed.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))
if not view.read_only:
    view.write(data)
else:
    print("Cannot modify read-only view")

size property

size: VecInt

⚠️ Deprecated, use view.bounding_box.in_mag(view.mag).size instead.

chunk

chunk(chunk_shape: VecIntLike, chunk_border_alignments: Optional[VecIntLike] = None, read_only: bool = False) -> Generator[View, None, None]

Generate a sequence of sub-views by chunking the current view.

Divides the view into smaller, regularly-sized chunks that can be processed independently. This is useful for parallel processing or when working with large datasets that don't fit in memory.

Parameters:

  • chunk_shape (VecIntLike) –

    Size of each chunk in Mag(1) coordinates.

  • chunk_border_alignments (Optional[VecIntLike], default: None ) –

    Alignment of chunk borders in Mag(1) coordinates. If None, aligns to (0, 0, 0). Defaults to None.

  • read_only (bool, default: False ) –

    Whether the generated chunks should be read-only. Defaults to False.

Yields:

  • View ( View ) –

    Sub-views representing each chunk of the original view.

Examples:

# let 'mag1' be a `MagView`
chunks = mag1.chunk(chunk_shape=(100, 100, 100), chunk_border_alignments=(50, 50, 50))

content_is_equal

content_is_equal(other: View, args: Optional[Namespace] = None, executor: Optional[Executor] = None) -> bool

Compare the content of this view with another view.

Performs a chunk-by-chunk comparison of the data in both views. This is more memory efficient than reading entire views at once for large datasets.

Parameters:

  • other (View) –

    The view to compare against.

  • args (Optional[Namespace], default: None ) –

    ⚠️ Deprecated. Arguments to pass to executor.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel comparison. If None, compares sequentially. Defaults to None.

  • progress_desc (Optional[str]) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

Returns:

  • bool ( bool ) –

    True if the content of both views is identical, False otherwise.

Examples:

# Compare views sequentially
if view1.content_is_equal(view2):
    print("Views are identical")
Note
  • Comparison is done chunk by chunk to manage memory usage
  • Views must have the same shape and data type
  • Returns False immediately if shapes or types don't match
  • Progress tracks total volume compared
  • Parallel execution can speed up comparison of large views

for_each_chunk

for_each_chunk(func_per_chunk: Callable[[Tuple[View, int]], None], chunk_shape: Optional[Vec3IntLike] = None, executor: Optional[Executor] = None, progress_desc: Optional[str] = None, *, chunk_size: Optional[Vec3IntLike] = None) -> None

Process each chunk of the view with a given function.

Divides the view into chunks and applies a function to each chunk, optionally in parallel. This is useful for processing large datasets in manageable pieces, with optional progress tracking and parallel execution.

Parameters:

  • func_per_chunk (Callable[[Tuple[View, int]], None]) –

    Function to apply to each chunk. Takes a tuple of (chunk_view, chunk_index) as argument. The chunk_index can be used for progress tracking or logging.

  • chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of each chunk in Mag(1) coordinates. If None, uses one chunk per file based on the dataset's file dimensions. Defaults to None.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel processing. If None, processes chunks sequentially. Defaults to None.

  • progress_desc (Optional[str], default: None ) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

  • chunk_size (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use chunk_shape instead. Defaults to None.

Examples:

from webknossos.utils import named_partial

# Define processing function
def process_chunk(args: Tuple[View, int], threshold: float) -> None:
    chunk_view, chunk_idx = args
    data = chunk_view.read()
    # Process data...
    chunk_view.write(processed_data)
    print(f"Processed chunk {chunk_idx}")

# Sequential processing with progress bar
view.for_each_chunk(
    named_partial(process_chunk, threshold=0.5),
    chunk_shape=(64, 64, 64),
    progress_desc="Processing chunks"
)
Note
  • Each chunk is processed independently, making this suitable for parallel execution
  • For non-read-only views, chunks must align with file boundaries
  • Progress tracking shows total volume processed
  • Memory usage depends on chunk_shape and parallel execution settings
  • When using an executor, ensure thread/process safety in func_per_chunk
  • The view's magnification affects the actual data resolution

for_zipped_chunks

for_zipped_chunks(func_per_chunk: Callable[[Tuple[View, View, int]], None], target_view: View, source_chunk_shape: Optional[Vec3IntLike] = None, target_chunk_shape: Optional[Vec3IntLike] = None, executor: Optional[Executor] = None, progress_desc: Optional[str] = None, *, source_chunk_size: Optional[Vec3IntLike] = None, target_chunk_size: Optional[Vec3IntLike] = None) -> None

Process paired chunks from source and target views simultaneously.

Chunks both the source (self) and target views, then applies a function to each corresponding pair of chunks. This is particularly useful for operations that transform data between views of different magnifications, like downsampling.

Parameters:

  • func_per_chunk (Callable[[Tuple[View, View, int]], None]) –

    Function to apply to each chunk pair. Takes (source_chunk, target_chunk, index) as arguments.

  • target_view (View) –

    The target view to write transformed data to.

  • source_chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of source chunks in Mag(1). If None, uses maximum of source and target file dimensions. Defaults to None.

  • target_chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of target chunks in Mag(1). If None, uses maximum of source and target file dimensions. Defaults to None.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel processing. If None, processes chunks sequentially. Defaults to None.

  • progress_desc (Optional[str], default: None ) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

  • source_chunk_size (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use source_chunk_shape instead. Defaults to None.

  • target_chunk_size (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use target_chunk_shape instead. Defaults to None.

Examples:

# Downsample data from Mag(1) to Mag(2)
def downsample_chunk(args: Tuple[View, View, int]) -> None:
    source_chunk, target_chunk, idx = args
    data = source_chunk.read()
    downsampled = downsample_data(data)  # Your downsampling function
    target_chunk.write(downsampled)
    print(f"Processed chunk pair {idx}")

# Process with default chunk sizes
mag1_view.for_zipped_chunks(
    downsample_chunk,
    mag2_view,
    progress_desc="Downsampling data"
)
Note
  • Source/target view size ratios must match chunk size ratios
  • Target chunks must align with file boundaries to avoid concurrent writes
  • Both views are chunked with matching strides
  • Progress tracks total volume processed
  • Memory usage depends on chunk sizes and parallel execution

get_buffered_slice_reader

get_buffered_slice_reader(offset: Optional[Vec3IntLike] = None, size: Optional[Vec3IntLike] = None, buffer_size: int = 32, dimension: int = 2, *, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None, use_logging: bool = False) -> BufferedSliceReader

Get a buffered reader for efficiently reading data slices.

Creates a BufferedSliceReader that allows efficient reading of data slices by buffering multiple slices in memory. This is particularly useful when reading large datasets slice by slice.

Parameters:

  • offset (Optional[Vec3IntLike], default: None ) –

    Starting position for reading in the dataset. Defaults to None.

  • size (Optional[Vec3IntLike], default: None ) –

    Size of the region to read in voxels. Defaults to None.

  • buffer_size (int, default: 32 ) –

    Number of slices to buffer in memory at once. Defaults to 32.

  • dimension (int, default: 2 ) –

    Axis along which to read slices (0=x, 1=y, 2=z). Defaults to 2 (z-axis).

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box in mag1 coordinates, relative to the current view's offset. Mutually exclusive with absolute_bounding_box. Defaults to None.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box in mag1 coordinates in absolute dataset coordinates. Mutually exclusive with relative_bounding_box. Defaults to None.

  • use_logging (bool, default: False ) –

    Whether to enable logging of read operations.

Returns:

  • BufferedSliceReader ( BufferedSliceReader ) –

    A reader object that yields data slices.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))

# Create a reader with default settings (z-slices)
with view.get_buffered_slice_reader() as reader:
    for slice_data in reader:
        process_slice(slice_data)

# Read y-slices with custom buffer size
with view.get_buffered_slice_reader(
    buffer_size=10,
    dimension=1,  # y-axis
    relative_offset=(10, 0, 0)
) as reader:
Note
  • Larger buffer sizes improve performance but use more memory
  • Choose dimension based on your data access pattern
  • Only one positioning parameter should be specified
  • The reader can be used as an iterator

get_buffered_slice_writer

get_buffered_slice_writer(offset: Optional[Vec3IntLike] = None, buffer_size: int = 32, dimension: int = 2, json_update_allowed: bool = True, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None, use_logging: bool = False) -> BufferedSliceWriter

Get a buffered writer for efficiently writing data slices.

Creates a BufferedSliceWriter that allows efficient writing of data slices by buffering multiple slices before performing the actual write operation.

Args: offset (Optional[Vec3IntLike]): Starting position for writing in the dataset. Defaults to None. buffer_size (int): Number of slices to buffer before performing a write. Defaults to 32. dimension (int): Axis along which to write slices (0=x, 1=y, 2=z). Defaults to 2 (z-axis). json_update_allowed (bool): Whether to allow updating the bounding box and datasource-properties.json. Should be False for parallel access. Defaults to True. relative_offset (Optional[Vec3IntLike]): Offset in mag1 coordinates, relative to the current view's position. Mutually exclusive with absolute_offset. Defaults to None. absolute_offset (Optional[Vec3IntLike]): Offset in mag1 coordinates in absolute dataset coordinates. Mutually exclusive with relative_offset. Defaults to None. relative_bounding_box (Optional[NDBoundingBox]): Bounding box in mag1 coordinates, relative to the current view's offset. Mutually exclusive with absolute_bounding_box. Defaults to None. absolute_bounding_box (Optional[NDBoundingBox]): Bounding box in mag1 coordinates in absolute dataset coordinates. Mutually exclusive with relative_bounding_box. Defaults to None. use_logging (bool): Whether to enable logging of write operations. Defaults to False.

Returns:

  • BufferedSliceWriter ( BufferedSliceWriter ) –

    A writer object for buffered slice writing.

Examples:

view = layer.get_mag("1").get_view(size=(100, 100, 10))

# Create a buffered writer with default settings
with view.get_buffered_slice_writer() as writer:
    # Write slices efficiently
    for z in range(10):
        slice_data = np.zeros((100, 100))  # Your slice data
        writer.send(slice_data)

# Create a writer with custom buffer size and offset
with view.get_buffered_slice_writer(
    buffer_size=5,
    relative_offset=(10, 10, 0)
)
Note
  • Larger buffer sizes can improve performance but use more memory
  • Remember to use the writer in a context manager
  • Only one positioning parameter should be specified

get_dtype

get_dtype() -> dtype

Returns the dtype per channel of the data. For example uint8.

get_view

get_view(offset: Optional[Vec3IntLike] = None, size: Optional[Vec3IntLike] = None, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None, read_only: Optional[bool] = None) -> View

Create a new view restricted to a specified region.

This method returns a new View instance that represents a subset of the current view's data. The new view can be specified using various coordinate systems and can optionally be made read-only.

Parameters:

  • offset (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use relative_offset or absolute_offset instead. Defaults to None.

  • size (Optional[Vec3IntLike], default: None ) –

    Size of the new view. Must be specified when using any offset parameter. Defaults to None.

  • relative_offset (Optional[Vec3IntLike], default: None ) –

    Offset relative to current view's position in Mag(1) coordinates. Must be used with size. Defaults to None.

  • absolute_offset (Optional[Vec3IntLike], default: None ) –

    Absolute offset in Mag(1) coordinates. Must be used with size. Defaults to None.

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box relative to current view's position in Mag(1) coordinates. Defaults to None.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Absolute bounding box in Mag(1) coordinates. Defaults to None.

  • read_only (Optional[bool], default: None ) –

    Whether the new view should be read-only. If None, inherits from parent view. Defaults to None.

Returns:

  • View ( View ) –

    A new View instance representing the specified region.

Raises:

  • AssertionError

    If: - Multiple positioning parameters are provided - Size is missing when using offset parameters - Non-read-only subview requested from read-only parent - Non-read-only subview extends beyond parent's bounds

Examples:

# Create view from MagView
mag1 = layer.get_mag("1")
view = mag1.get_view(absolute_offset=(10, 20, 30), size=(100, 200, 300))

# Create subview within bounds
sub_view = view.get_view(
    relative_offset=(50, 60, 70),
    size=(10, 120, 230)
)

# Create read-only subview (can extend beyond bounds)
large_view = view.get_view(
    relative_offset=(50, 60, 70),
    size=(999, 120, 230),
    read_only=True
)

# Use bounding box instead of offset+size
bbox = BoundingBox((10, 10, 0), (50, 50, 10))
bbox_view = view.get_view(relative_bounding_box=bbox)
Note
  • Use only one method to specify the region (offset+size or bounding_box)
  • All coordinates are in Mag(1) except for the deprecated offset
  • Non-read-only views must stay within parent view's bounds
  • Read-only views can extend beyond parent view's bounds
  • The view's magnification affects the actual data resolution

map_chunk

map_chunk(func_per_chunk: Callable[[View], Any], chunk_shape: Optional[Vec3IntLike] = None, executor: Optional[Executor] = None, progress_desc: Optional[str] = None) -> List[Any]

Process each chunk of the view and collect results.

Similar to for_each_chunk(), but collects and returns the results from each chunk. Useful for parallel data analysis or feature extraction where results need to be aggregated.

Parameters:

  • func_per_chunk (Callable[[View], Any]) –

    Function to apply to each chunk. Takes a chunk view as argument and returns a result of any type.

  • chunk_shape (Optional[Vec3IntLike], default: None ) –

    Size of each chunk in Mag(1) coordinates. If None, uses one chunk per file based on the dataset's file dimensions. Defaults to None.

  • executor (Optional[Executor], default: None ) –

    Executor for parallel processing. If None, processes chunks sequentially. Defaults to None.

  • progress_desc (Optional[str], default: None ) –

    Description for progress bar. If None, no progress bar is shown. Defaults to None.

Returns:

  • List[Any]

    List[Any]: List of results from processing each chunk, in chunk order.

Examples:

from webknossos.utils import named_partial

# Calculate statistics per chunk
def chunk_statistics(view: View, min_value: float) -> Dict[str, float]:
    data = view.read()
    return {
        "mean": data[data > min_value].mean(),
        "std": data[data > min_value].std(),
        "volume": view.bounding_box.volume()
    }

# Sequential processing
stats = view.map_chunk(
    named_partial(chunk_statistics, min_value=0.1),
    chunk_shape=(128, 128, 128)
)

# Aggregate results
total_volume = sum(s["volume"] for s in stats)
mean_values = [s["mean"] for s in stats]
Note
  • Results are collected in memory, consider memory usage for large datasets
  • Each chunk is processed independently, suitable for parallel execution
  • For non-read-only views, chunks must align with file boundaries
  • When using an executor, ensure thread/process safety in func_per_chunk
  • Results maintain chunk order regardless of execution order

read

read(offset: Optional[Vec3IntLike] = None, size: Optional[Vec3IntLike] = None, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None) -> ndarray

Read data from the view at a specified location.

This method provides flexible ways to read data from the view's region. If no parameters are provided, it reads the entire view's bounding box. The region to read can be specified using either offset+size combinations or bounding boxes.

Parameters:

  • offset (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use relative_offset or absolute_offset instead. Defaults to None.

  • size (Optional[Vec3IntLike], default: None ) –

    Size of region to read. Specified in Mag(1) coordinates unless used with deprecated offset. Defaults to None.

  • relative_offset (Optional[Vec3IntLike], default: None ) –

    Offset relative to the view's position in Mag(1) coordinates. Must be used with size. Defaults to None.

  • absolute_offset (Optional[Vec3IntLike], default: None ) –

    Absolute offset in Mag(1) coordinates. Must be used with size. Defaults to None.

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box relative to the view's position in Mag(1) coordinates. Defaults to None.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Absolute bounding box in Mag(1) coordinates. Defaults to None.

Returns:

  • ndarray

    np.ndarray: The requested data as a numpy array. The shape will be either (channels, x, y, z) for multi-channel data or (x, y, z) for single-channel data. Areas outside the dataset are zero-padded.

Raises:

  • AssertionError

    If incompatible parameters are provided (e.g., both offset+size and bounding_box) or if the requested region is empty.

Examples:

# Read entire view's data
view = layer.get_mag("1").get_view(size=(100, 100, 10))
data = view.read()  # Returns (x, y, z) array for single-channel data

# Read with relative offset and size
data = view.read(
    relative_offset=(10, 10, 0),  # Offset from view's position
    size=(50, 50, 10)            # Size in Mag(1) coordinates
)

# Read with absolute bounding box
bbox = BoundingBox((0, 0, 0), (100, 100, 10))
data = view.read(absolute_bounding_box=bbox)

# Read from multi-channel data
view = color_layer.get_mag("1").get_view(size=(100, 100, 10))
data = view.read()  # Returns (channels, x, y, z) array
Note
  • Use only one method to specify the region (offset+size or bounding_box)
  • All coordinates are in Mag(1) except for the deprecated offset parameter
  • For multi-channel data, the returned array has shape (C, X, Y, Z)
  • For single-channel data, the returned array has shape (X, Y, Z)
  • Regions outside the dataset are automatically zero-padded
  • The view's magnification affects the actual data resolution
  • Data shape must match the target region size

read_bbox

read_bbox(bounding_box: Optional[BoundingBox] = None) -> ndarray

⚠️ Deprecated. Please use read() with relative_bounding_box or absolute_bounding_box in Mag(1) instead. The user can specify the bounding_box in the current mag of the requested data. See read() for more details.

read_xyz

read_xyz(relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None) -> ndarray

Read n-dimensional data and convert it to 3D XYZ format.

This method is designed for handling n-dimensional data (n > 3) and converting it to strictly 3D data ordered as (X, Y, Z). It is primarily used internally by operations that require 3D data like downsampling, upsampling, and compression.

When provided with a BoundingBox where additional dimensions (beyond X, Y, Z) have a shape of 1, it returns an array containing only the 3D spatial data. This ensures compatibility with operations that expect purely 3-dimensional input.

Parameters:

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box relative to view's position in Mag(1) coordinates. Defaults to None.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Absolute bounding box in Mag(1) coordinates. Defaults to None.

Returns:

  • ndarray

    np.ndarray: The requested data as a numpy array with dimensions ordered as (channels, X, Y, Z) for multi-channel data or (X, Y, Z) for single-channel data. Areas outside the dataset are zero-padded.

Examples:

# Read entire view's data in XYZ order
view = layer.get_mag("1").get_view(size=(100, 100, 10))
xyz_data = view.read_xyz()  # Returns (X, Y, Z) array

# Read with relative bounding box
bbox = NDBoundingBox((10, 10, 0), (50, 50, 10), axis=("x", "y", "z"), index=(1, 2, 3))
xyz_data = view.read_xyz(relative_bounding_box=bbox)
Note
  • If no bounding box is provided, reads the entire view's region
  • Only one bounding box parameter should be specified
  • The returned array's axes are ordered differently from read()
  • All coordinates are in Mag(1)

write

write(data: ndarray, offset: Optional[Vec3IntLike] = None, json_update_allowed: bool = True, *, relative_offset: Optional[Vec3IntLike] = None, absolute_offset: Optional[Vec3IntLike] = None, relative_bounding_box: Optional[NDBoundingBox] = None, absolute_bounding_box: Optional[NDBoundingBox] = None) -> None

Write data to the view at a specified location.

This method writes array data to the view's region. If no position parameters are provided, data is written to the view's bounding box. The write location can be specified using either offset parameters or bounding boxes.

Parameters:

  • data (ndarray) –

    The data to write. For single-channel data, shape should be (x, y, y). For multi-channel data, shape should be (channels, x, y, z). Shape must match the target region size.

  • offset (Optional[Vec3IntLike], default: None ) –

    ⚠️ Deprecated. Use relative_offset or absolute_offset instead. Defaults to None.

  • json_update_allowed (bool, default: True ) –

    Whether to allow updating JSON metadata. Set to False when executing writes in parallel. Defaults to True.

  • relative_offset (Optional[Vec3IntLike], default: None ) –

    Offset relative to view's position in Mag(1) coordinates. Defaults to None.

  • absolute_offset (Optional[Vec3IntLike], default: None ) –

    Absolute offset in Mag(1) coordinates. Defaults to None.

  • relative_bounding_box (Optional[NDBoundingBox], default: None ) –

    Bounding box relative to view's position in Mag(1) coordinates. Defaults to None.

  • absolute_bounding_box (Optional[NDBoundingBox], default: None ) –

    Absolute bounding box in Mag(1) coordinates. Defaults to None.

Raises:

  • AssertionError

    If: - View is read-only - Data dimensions don't match the target region - Number of channels doesn't match the dataset - Write region is outside the view's bounding box - Multiple positioning parameters are provided

Examples:

import numpy as np
from webknossos.dataset import Dataset, View

# Write to entire view's region
view = layer.get_mag("1").get_view(size=(100, 100, 10))
data = np.zeros(view.bounding_box.in_mag(view.mag).size)
view.write(data)

# Write with relative offset
data = np.ones((50, 50, 5))  # Smaller region
view.write(data, relative_offset=(10, 10, 0))

# Write multi-channel data
rgb_data = np.zeros((3, 100, 100, 10))  # 3 channels
rgb_view = color_layer.get_mag("1").get_view(size=(100, 100, 10))
rgb_view.write(rgb_data)

# Write with absolute bounding box
bbox = BoundingBox((0, 0, 0), (100, 100, 10))
view.write(data, absolute_bounding_box=bbox)
Note
  • Only one positioning parameter (offset or bounding_box) should be used
  • All coordinates are in Mag(1) except for the deprecated offset
  • For compressed data, writes should align with compression blocks
  • For segmentation layers, call refresh_largest_segment_id() after writing
  • The view's magnification affects the actual data resolution
  • Data shape must match the target region size