Skip to content

mpcompress.utils.tensor_ops

border_pad

border_pad(x, patch_size)

Pad a tensor on the right and bottom borders to make dimensions divisible by patch_size.

Adds padding only to the right (width) and bottom (height) edges, ensuring both dimensions become multiples of patch_size.

Parameters:

Name Type Description Default
x Tensor

Input tensor with shape (B, C, H, W).

required
patch_size int

Patch size. Height and width will be padded to be divisible by patch_size.

required

Returns:

Name Type Description
x_padded Tensor

Padded tensor with shape (B, C, new_H, new_W), where new_H and new_W are multiples of patch_size.

center_crop

center_crop(x, padding)

Remove center padding from a tensor.

Crops the tensor by removing the padding that was added by center_pad. Uses negative padding values to crop from the edges.

Parameters:

Name Type Description Default
x Tensor

Padded tensor to crop.

required
padding tuple

Tuple of (padding_left, padding_right, padding_top, padding_bottom) returned by center_pad.

required

Returns:

Name Type Description
x_cropped Tensor

Cropped tensor with original spatial dimensions restored.

center_pad

center_pad(x, p)

Pad a tensor to make its spatial dimensions divisible by p, using center padding.

Pads the tensor symmetrically (centered) so that both height and width become multiples of p. The padding is distributed evenly on both sides when possible, with any remainder added to the right/bottom.

Parameters:

Name Type Description Default
x Tensor

Input tensor with shape (B, C, H, W).

required
p int

Padding divisor. Height and width will be padded to be divisible by p.

required

Returns:

Name Type Description
x_padded Tensor

Padded tensor with shape (B, C, new_H, new_W).

padding tuple

Tuple of (padding_left, padding_right, padding_top, padding_bottom) that can be used with center_crop to restore original size.

tensor2image

tensor2image(x: Tensor) -> Image.Image

Convert a tensor to a PIL Image.

Clamps tensor values to [0, 1] range, removes dimensions of size 1, and converts to PIL Image format.

Parameters:

Name Type Description Default
x Tensor

Input tensor with values in [0, 1] range.

required

Returns:

Name Type Description
image Image

The converted PIL Image.