Functional implementation of cropping a MetaTensor. This function operates eagerly or lazily according to ``lazy`` (default ``False``). Args: img: data to be transformed, assuming `img` is channel-first and cropping doesn't apply to the channel dim. slices: the crop sli
(img: torch.Tensor, slices: tuple[slice, ...], lazy: bool, transform_info: dict)
| 215 | |
| 216 | |
| 217 | def crop_func(img: torch.Tensor, slices: tuple[slice, ...], lazy: bool, transform_info: dict) -> torch.Tensor: |
| 218 | """ |
| 219 | Functional implementation of cropping a MetaTensor. This function operates eagerly or lazily according |
| 220 | to ``lazy`` (default ``False``). |
| 221 | |
| 222 | Args: |
| 223 | img: data to be transformed, assuming `img` is channel-first and cropping doesn't apply to the channel dim. |
| 224 | slices: the crop slices computed based on specified `center & size` or `start & end` or `slices`. |
| 225 | lazy: a flag indicating whether the operation should be performed in a lazy fashion or not. |
| 226 | transform_info: a dictionary with the relevant information pertaining to an applied transform. |
| 227 | """ |
| 228 | img_size = img.peek_pending_shape() if isinstance(img, MetaTensor) else img.shape[1:] |
| 229 | spatial_rank = img.peek_pending_rank() if isinstance(img, MetaTensor) else 3 |
| 230 | cropped = np.asarray([[s.indices(o)[0], o - s.indices(o)[1]] for s, o in zip(slices[1:], img_size)]) |
| 231 | extra_info = {"cropped": cropped.flatten().tolist()} |
| 232 | to_shift = [] |
| 233 | for i, s in enumerate(ensure_tuple(slices)[1:]): |
| 234 | if s.start is not None: |
| 235 | to_shift.append(img_size[i] + s.start if s.start < 0 else s.start) |
| 236 | else: |
| 237 | to_shift.append(0) |
| 238 | shape = [s.indices(o)[1] - s.indices(o)[0] for s, o in zip(slices[1:], img_size)] |
| 239 | meta_info = TraceableTransform.track_transform_meta( |
| 240 | img, |
| 241 | sp_size=shape, |
| 242 | affine=create_translate(spatial_rank, to_shift), |
| 243 | extra_info=extra_info, |
| 244 | orig_size=img_size, |
| 245 | transform_info=transform_info, |
| 246 | lazy=lazy, |
| 247 | ) |
| 248 | out = convert_to_tensor(img.as_tensor() if isinstance(img, MetaTensor) else img, track_meta=get_track_meta()) |
| 249 | if lazy: |
| 250 | return out.copy_meta_from(meta_info) if isinstance(out, MetaTensor) else meta_info # type: ignore |
| 251 | out = out[slices] |
| 252 | return out.copy_meta_from(meta_info) if isinstance(out, MetaTensor) else out # type: ignore |
no test coverage detected
searching dependent graphs…