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

Method crop_pad

monai/transforms/croppad/array.py:884–926  ·  view source on GitHub ↗

Crop and pad based on the bounding box.

(
        self,
        img: torch.Tensor,
        box_start: np.ndarray,
        box_end: np.ndarray,
        mode: str | None = None,
        lazy: bool = False,
        **pad_kwargs,
    )

Source from the content-addressed store, hash-verified

882 return box_start_, box_end_
883
884 def crop_pad(
885 self,
886 img: torch.Tensor,
887 box_start: np.ndarray,
888 box_end: np.ndarray,
889 mode: str | None = None,
890 lazy: bool = False,
891 **pad_kwargs,
892 ) -> torch.Tensor:
893 """
894 Crop and pad based on the bounding box.
895
896 """
897 slices = self.compute_slices(roi_start=box_start, roi_end=box_end)
898 cropped = super().__call__(img=img, slices=slices, lazy=lazy)
899 pad_to_start = np.maximum(-box_start, 0)
900 pad_to_end = np.maximum(
901 box_end - np.asarray(img.peek_pending_shape() if isinstance(img, MetaTensor) else img.shape[1:]), 0
902 )
903 pad = list(chain(*zip(pad_to_start.tolist(), pad_to_end.tolist())))
904 pad_width = BorderPad(spatial_border=pad).compute_pad_width(
905 cropped.peek_pending_shape() if isinstance(cropped, MetaTensor) else cropped.shape[1:]
906 )
907 ret = self.padder.__call__(img=cropped, to_pad=pad_width, mode=mode, lazy=lazy, **pad_kwargs)
908 # combine the traced cropping and padding into one transformation
909 # by taking the padded info and placing it in a key inside the crop info.
910 if get_track_meta() and isinstance(ret, MetaTensor):
911 if not lazy:
912 ret.applied_operations[-1][TraceKeys.EXTRA_INFO]["pad_info"] = ret.applied_operations.pop()
913 else:
914 pad_info = ret.pending_operations.pop()
915 crop_info = ret.pending_operations.pop()
916 extra = crop_info[TraceKeys.EXTRA_INFO]
917 extra["pad_info"] = pad_info
918 self.push_transform(
919 ret,
920 orig_size=crop_info.get(TraceKeys.ORIG_SIZE),
921 sp_size=pad_info[LazyAttr.SHAPE],
922 affine=crop_info[LazyAttr.AFFINE] @ pad_info[LazyAttr.AFFINE],
923 lazy=lazy,
924 extra_info=extra,
925 )
926 return ret
927
928 def __call__( # type: ignore[override]
929 self, img: torch.Tensor, mode: str | None = None, lazy: bool | None = None, **pad_kwargs

Callers 2

__call__Method · 0.95
__call__Method · 0.80

Calls 9

get_track_metaFunction · 0.90
BorderPadClass · 0.85
peek_pending_shapeMethod · 0.80
popMethod · 0.80
push_transformMethod · 0.80
getMethod · 0.80
compute_slicesMethod · 0.45
__call__Method · 0.45
compute_pad_widthMethod · 0.45

Tested by

no test coverage detected