spatialdata icon indicating copy to clipboard operation
spatialdata copied to clipboard

Add delayed Z-dimension scaling option for 3D image multiscales

Open Copilot opened this issue 5 months ago • 0 comments

This PR adds a new delay_z_scaling parameter to Image3DModel.parse() that enables delayed scaling along the Z dimension for 3D images. This is particularly useful for 3D image visualization where preserving Z resolution longer is beneficial.

Problem

When creating multiscale representations of 3D images, the default behavior scales all dimensions (X, Y, Z) uniformly. For certain use cases, especially 3D rendering and visualization, it's desirable to preserve Z resolution longer by scaling only X and Y dimensions initially.

Solution

Added a new optional parameter delay_z_scaling: bool = False to Image3DModel.parse() that:

  1. Scales only X and Y dimensions by factor 2 until min(X_size, Y_size) < original_Z_size
  2. Then scales all dimensions (X, Y, Z) by factor 2 for subsequent levels
  3. Automatically computes appropriate scale factors when enabled
  4. Maintains backward compatibility (disabled by default)

Example Usage

import numpy as np
from spatialdata.models import Image3DModel

# Create 3D image data (C, Z, Y, X)
data_3d = np.random.random((12, 194, 3181, 4045)).astype(np.float32)

# Standard multiscale scaling (all dimensions scaled equally)
standard = Image3DModel.parse(data_3d, scale_factors=[2, 2, 2])

# New delayed Z scaling feature
delayed_z = Image3DModel.parse(data_3d, delay_z_scaling=True)

Resulting Multiscale Structure

For the example data [12, 194, 3181, 4045] (C, Z, Y, X):

  • Level 0: [12, 194, 3181, 4045] (original)
  • Level 1-4: [12, 194, Y/2, X/2] (only X,Y scaled, Z preserved)
  • Level 5+: [12, Z/2, Y/2, X/2] (all dimensions scaled)

Z scaling begins when min(X,Y) = 99 < original_Z = 194.

Implementation Details

  • Overrides the parse() method in Image3DModel class
  • Adds _compute_delayed_z_scale_factors() helper method with the scaling algorithm
  • Warns users when scale_factors is provided alongside delay_z_scaling=True
  • Includes comprehensive tests for the new functionality
  • Maintains full backward compatibility

Testing

Added tests that verify:

  • Correct scale factor computation and resulting shapes
  • Warning when conflicting parameters are provided
  • Edge cases (small images, invalid dimensions)
  • Backward compatibility when delay_z_scaling=False

Fixes #954.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot avatar Jul 11 '25 16:07 Copilot