Skip to content

fix loadtiffd spatial shape #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

fanweiya
Copy link

@fanweiya fanweiya commented Apr 9, 2025

Description:

This PR addresses a bug in the vista2d/components.py:LoadTiffd transform that causes RuntimeError: each element in list of batch should be of equal size during data collation when using pad_list_data_collate or similar functions.

Problem:

The current implementation calculates and stores the ImageMetaKey.SPATIAL_SHAPE metadata before normalizing the image array's dimensions and channel count. Input image files can have different original dimensions (e.g., 2D grayscale (H, W), 3D channels-last (H, W, C), or 3D channels-first (C, H, W)). This leads to the stored spatial_shape metadata being a tuple of inconsistent lengths (e.g., length 2 or length 3) across different samples in the dataset.

When the DataLoader attempts to collate a batch containing samples with different spatial_shape lengths, the default collation logic for metadata (monai.data.utils.collate_meta_tensor_fn -> torch.utils.data._utils.collate.default_collate) fails because it cannot stack tuples/lists of varying sizes.

Solution:

The fix implemented in this PR modifies LoadTiffd as follows:

  1. The calculation of the shape to be stored in ImageMetaKey.SPATIAL_SHAPE is moved to after all image array manipulations (loading, transposing, adding/repeating/selecting channels).
  2. The code now ensures the image array is consistently represented in a 3D (C, H, W) format internally before metadata creation.
  3. It explicitly extracts only the spatial dimensions (the last two dimensions, H and W) from the final processed 3D array.
  4. This extracted (H, W) tuple, which always has a length of 2, is stored as the value for ImageMetaKey.SPATIAL_SHAPE in the MetaTensor.

Outcome:

This change guarantees that the spatial_shape metadata associated with loaded images has a consistent length (always 2) across all samples, regardless of the original file's dimensions. This resolves the downstream collation error. Robustness for handling different input dimensions (2D, 3D channels-last/first, >3D) has also been slightly improved with added logging.

fanweiya and others added 2 commits April 9, 2025 17:16
Ensure consistent spatial_shape metadata in LoadTiffd

Signed-off-by: fanweiya <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant