torch.nn.functional.interpolate(最近邻插值,双线性插值)
文章目录
- 一、torch.nn.functional.interpolate
一、torch.nn.functional.interpolate
torch.nn.functional.interpolate函数是PyTorch中用于对张量进行插值的功能。它支持多种参数和选项,以灵活地调整输入张量的大小或进行特征图的插值操作。
torch.nn.functional.interpolate(input, size=None, scale_factor=None,
mode='nearest', align_corners=None, recompute_scale_factor=None)
参数解释:
- input:输入张量,可以是四维的,比如(batch_size, channels, height, width)。
- size:输出张量的目标大小,可以是一个int或tuple。如果给定,scale_factor应为None。指定目标大小后,会将输入张量插值为指定大小。
- scale_factor:输出张量的缩放因子,可以是一个浮点数或tuple。如果给定,size应为None。指定缩放因子后,会按照指定比例缩放输入张量。
- mode:插值方式,包括’nearest’(最近邻插值)、‘bilinear’(双线性插值)、‘bicubic’(双三次插值)等。选择不同的插值模式会影响插值的效果。
- align_corners:对于双线性插值模式,指定是否要对齐角落像素。设置为True时,会对齐角落像素,有助于保持图像的几何形状。
- recompute_scale_factor:一个布尔值,指示是否需要重新计算缩放因子。默认为False。
import torch
import torch.nn.functional as Finput_tensor = torch.tensor([[[[1.0, 2.0],[3.0, 4.0]]]])# Nearest Neighbor Interpolation
output_nearest = F.interpolate(input_tensor, scale_factor=2, mode='nearest')
print("Nearest Neighbor Interpolation:")
print(output_nearest)# Bilinear Interpolation
output_bilinear = F.interpolate(input_tensor, scale_factor=2, mode='bilinear',align_corners=True)
print("\nBilinear Interpolation:")
print(output_bilinear)# Bicubic Interpolation
output_bicubic = F.interpolate(input_tensor, scale_factor=2, mode='bicubic')
print("\nBicubic Interpolation:")
print(output_bicubic)
Nearest Neighbor Interpolation:
tensor([[[[1., 1., 2., 2.],[1., 1., 2., 2.],[3., 3., 4., 4.],[3., 3., 4., 4.]]]])
Bilinear Interpolation:
tensor([[[[1.0000, 1.2500, 1.7500, 2.0000],[1.5000, 1.7500, 2.2500, 2.5000],[2.5000, 2.7500, 3.2500, 3.5000],[3.0000, 3.2500, 3.7500, 4.0000]]]])
Bicubic Interpolation:
tensor([[[[0.6836, 1.0156, 1.5625, 1.8945],[1.3477, 1.6797, 2.2266, 2.5586],[2.4414, 2.7734, 3.3203, 3.6523],[3.1055, 3.4375, 3.9844, 4.3164]]]])