2021-09-09

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

从输入图像中选择一个最近的像素.忽略所有其他输入像素.

NEAREST效果

PIL.Image.BILINEAR

要调整大小,请对所有可能影响输出值的像素使用线性插值计算输出像素值.对于其他变换,使用输入图像中2x2环境上的线性插值.

BILINEAR效果

PIL.Image.BICUBIC

要调整大小,请对所有可能影响输出值的像素使用三次插值法计算输出像素值.对于其他变换,在输入图像中使用4x4环境的三次插值.

BICUBIC效果

官方给出了这样的评价:

FilterDownscaling qualityUpscaling qualityPerformance
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

https://www.it1352.com/1748564.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值