Pytorch中 Resize()函数的插值计算
完整代码见:https://github.com/xmu-xiaoma666/CVAlgorithm
欢迎大家Star~
1、读取图片
读取图片有三种方式
使用skimage读取图像
imgpath='./data/person.jpg'
# 使用skimage读取图像
img_skimage = io.imread(imgpath) # skimage.io imread()-----np.ndarray, (H x W x C), [0, 255],RGB
print(img_skimage.shape)
print(type(img_skimage))
### (427, 640, 3)
### <class 'numpy.ndarray'
使用opencv读取图像
# 使用opencv读取图像
img_cv = cv2.imread(imgpath) # cv2.imread()------np.array, (H x W xC), [0, 255], BGR
print(img_cv.shape)
print(type(img_cv))
### (427, 640, 3)
### <class 'numpy.ndarray'
使用PIL读取
# 使用PIL读取
img_pil = Image.open(imgpath) # PIL.Image.Image对象
img_pil_1 = np.array(img_pil) # (H x W x C), [0, 255], RGB
print(img_pil_1.shape)
print(type(img_pil_1))
### (427, 640, 3)
### <class 'numpy.ndarray'
2、用Resize函数进行缩放
from torchvision.transforms import Compose, CenterCrop, ToTensor, Resize
resize=Compose([
Resize((224,224)),
ToTensor()
])
print(resize(img_pil).shape)
### torch.Size([3, 224, 224])
3、解析Resize函数
如图所示,Resize函数有两个参数,第一个是size,很好理解,就是缩放大小。第二个是interplolation,是插值方法,有多重选择,下面我们来看一下,适用于tensor的有三种选择PIL.Image.NEAREST
, PIL.Image.BILINEAR
,PIL.Image.BICUBIC
.
原图:
PIL.Image.NEAREST
从输入图像中选择一个最近的像素.忽略所有其他输入像素.
PIL.Image.BILINEAR
要调整大小,请对所有可能影响输出值的像素使用线性插值计算输出像素值.对于其他变换,使用输入图像中2x2环境上的线性插值.
PIL.Image.BICUBIC
要调整大小,请对所有可能影响输出值的像素使用三次插值法计算输出像素值.对于其他变换,在输入图像中使用4x4环境的三次插值.
官方给出了这样的评价:
Filter | Downscaling quality | Upscaling quality | Performance |
---|---|---|---|
NEAREST | ⭐⭐⭐⭐⭐ | ||
BILINEAR | ⭐ | ⭐ | ⭐⭐⭐ |
BICUBIC | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
Reference
https://www.jianshu.com/p/cfca9c4338e7
[https://pytorch.org/docs/1.7.1/torchvision/transforms.html?highlight=transforms resize#torchvision.transforms.Resize](https://pytorch.org/docs/1.7.1/torchvision/transforms.html?highlight=transforms resize#torchvision.transforms.Resize)
https://pillow.readthedocs.io/en/latest/handbook/concepts.html#PIL.Image.NEAREST