MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / SplitDim

Class SplitDim

monai/transforms/utility/array.py:291–334  ·  view source on GitHub ↗

Given an image of size X along a certain dimension, return a list of length X containing images. Useful for converting 3D images into a stack of 2D images, splitting multichannel inputs into single channels, for example. Note: `torch.split`/`np.split` is used, so the outputs are vi

Source from the content-addressed store, hash-verified

289
290
291class SplitDim(Transform, MultiSampleTrait):
292 """
293 Given an image of size X along a certain dimension, return a list of length X containing
294 images. Useful for converting 3D images into a stack of 2D images, splitting multichannel inputs into
295 single channels, for example.
296
297 Note: `torch.split`/`np.split` is used, so the outputs are views of the input (shallow copy).
298
299 Args:
300 dim: dimension on which to split
301 keepdim: if `True`, output will have singleton in the split dimension. If `False`, this
302 dimension will be squeezed.
303 update_meta: whether to update the MetaObj in each split result.
304 """
305
306 backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
307
308 def __init__(self, dim: int = -1, keepdim: bool = True, update_meta=True) -> None:
309 self.dim = dim
310 self.keepdim = keepdim
311 self.update_meta = update_meta
312
313 def __call__(self, img: torch.Tensor) -> list[torch.Tensor]:
314 """
315 Apply the transform to `img`.
316 """
317 n_out = img.shape[self.dim]
318 if isinstance(img, torch.Tensor):
319 outputs = list(torch.split(img, 1, self.dim))
320 else:
321 outputs = np.split(img, n_out, self.dim)
322 for idx, item in enumerate(outputs):
323 if not self.keepdim:
324 outputs[idx] = item.squeeze(self.dim)
325 if self.update_meta and isinstance(img, MetaTensor):
326 if not isinstance(item, MetaTensor):
327 item = MetaTensor(item, meta=img.meta)
328 if self.dim == 0: # don't update affine if channel dim
329 continue
330 ndim = len(item.affine)
331 shift = torch.eye(ndim, device=item.affine.device, dtype=item.affine.dtype)
332 shift[self.dim - 1, -1] = idx
333 item.affine = item.affine @ shift
334 return outputs
335
336
337class CastToType(Transform):

Callers 3

__init__Method · 0.90
test_correct_shapeMethod · 0.90
test_singletonMethod · 0.90

Calls

no outgoing calls

Tested by 2

test_correct_shapeMethod · 0.72
test_singletonMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…