本文讲解如何用pytorch包进行插值,不仅限于函数插值,还包括图像的插值(即缩放)。

假设我有一个图像a,其大小为(4,4):

import torch
import torch.nn as nn
a = torch.randint(10,(4,4))
a = a / torch.max(a)[0]
# 打印图片
plt.imshow(a)

out:
在这里插入图片描述

但是我想利用插值技术把它分辨率变高,比如变成(28,28)的大小,那么我们可以这么做,记住,一定要把原图像扩充成4维,按照文档的说法是:The input dimensions are interpreted in the form: mini-batch x channels x [optional depth] x [optional height] x width.,所以这里我需要在size前面添加一个channel维度和depth维度。

b = nn.functional.interpolate(a.unsqueeze(0).unsqueeze(0), (28, 28), 
mode='bilinear', align_corners=True)
# 打印插值后的图像,别忘了修改shape
plt.imshow(b.resize(28,28))

out:
在这里插入图片描述

我们来看一下这个函数的具体参数吧。

Definition : interpolate(input: Any, size: Optional[Any]=…, scale_factor: Optional[Any]=…, mode: str=…, align_corners: Optional[Any]=…)

input (Tensor): the input tensor size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):

output spatial size.

scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple. mode (str): algorithm used for upsampling:

‘nearest’ | ‘linear’ | ‘bilinear’ | ‘bicubic’ | ‘trilinear’ | ‘area’. Default: ‘nearest’

align_corners (bool, optional): Geometrically, we consider the pixels of the
input and output as squares rather than points. If set to True, the input and output tensors are aligned by the center points of their corner pixels, preserving the values at the corner pixels. If set to False, the input and output tensors are aligned by the corner points of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values, making this operation independent of input size when scale_factor is kept the same. This only has an effect when mode is ‘linear’, ‘bilinear’, ‘bicubic’ or ‘trilinear’. Default: False

recompute_scale_factor (bool, optional): recompute the scale_factor for use in the
interpolation calculation. When scale_factor is passed as a parameter, it is used to compute the output_size. If recompute_scale_factor is `False or not specified, the passed-in scale_factor will be used in the interpolation computation. Otherwise, a new scale_factor will be computed based on the output and input sizes for use in the interpolation computation (i.e. the computation will be identical to if the computed output_size were passed-in explicitly). Note that when scale_factor is floating-point, the recomputed scale_factor may differ from the one passed in due to rounding and precision issues.