imresize_and_pad_if_need
-
Description: Resizes an image to fit within
(max_h, max_w), and pads to the fixed target size when needed. -
Parameters
- img (
np.ndarray): Input image. - max_h (
int): Max output height (and the fixed padded height). - max_w (
int): Max output width (and the fixed padded width). - interpolation (
str | int | INTER): Resize interpolation. Default isINTER.BILINEAR. - pad_value (
int | tuple[int, int, int] | None): Padding value. For 3-channel images, you can pass an int or a tuple (OpenCV convention: BGR). Default is 0. - pad_mode (
str | int | BORDER): Padding mode. Default isBORDER.CONSTANT. - return_scale (
bool): Whether to return the resize scale. Default isFalse.
- img (
-
Returns
- When
return_scale=False: returnsnp.ndarray. - When
return_scale=True: returns(np.ndarray, float), where float isscale = min(max_h/raw_h, max_w/raw_w).
- When
-
Notes
- Padding is applied to bottom and right only (top=0, left=0).
- The image will be downscaled when
max_h/max_wis smaller than the original, and upscaled when larger.
-
Example
import capybara as cb
img = cb.imread('lena.png')
out, scale = cb.imresize_and_pad_if_need(
img,
max_h=640,
max_w=640,
pad_value=0,
return_scale=True,
)
print(out.shape, scale)