resize函数用于改变图像的尺寸,可以放大或缩小图像。通过指定目标大小或缩放因子,用户可以灵活调整图像的宽度和高度。Torchvision支持多种插值方法,本文档针对bilinear和bicubic两种插值方式进行优化,保证图像在缩放过程中尽可能保持质量。
1 | torchvision.transforms.resize(size, interpolation=InterpolationMode.BILINEAR,max_size=None, antialias=True) |
参数名 |
描述 |
取值范围 |
输入/输出 |
---|---|---|---|
size |
序列或int型数字,表征输出图像的大小(宽度和高度),如(width, height)。如果设置为int型数,则表征图像较小边缘的大小。 |
(0, INT_MAX] |
输入 |
interpolation |
插值方式,默认为BILINEAR。支持InterpolationMode.NEAREST、InterpolationMode.NEAREST_EXACT、InterpolationMode.BILINEAR和InterpolationMode.BICUBIC四种,本文档对InterpolationMode.BILINEAR和InterpolationMode.BICUBIC两种方法进行优化。 |
InterpolationMode.BILINEAR、InterpolationMode.BICUBIC |
输入 |
max_size |
可选值,调整大小的图像的较长边所允许的最大值,当size输入为int时,若图像长边大于max_size,则根据max_size调整大小。 |
(0, INT_MAX] |
输入 |
antialias |
可选值,对PIL图像作用,对tensor无影响,默认为True。 |
bool |
输入 |
错误码 |
描述 |
---|---|
KP_PT_STS_NULL_PTR_ERR |
指针内存分配错误。 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import numpy as np import torch from torchvision import transforms # 定义源数据 src = np.array([[1, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 0, 0, 0, 0]], dtype=np.float32) # 将NumPy数组转换为Tensor,并添加通道信息 src_tensor = torch.from_numpy(src).unsqueeze(0).unsqueeze(0) # 定义目标尺寸 size = (4, 4) # 创建图像尺寸调整转换 resize = transforms.Resize(size) # 应用图像尺寸调整转换 resized_src_tensor = resize(src_tensor) #显示矩阵 print(resized_src_tensor) |
运行结果:
1 2 3 4 | tensor([[[[0.6250, 0.2500, 0.2500, 0.0625], [0.2500, 0.8264, 0.8264, 0.2500], [0.2500, 0.8264, 0.8264, 0.2500], [0.6250, 0.2500, 0.2500, 0.0625]]]]) |