让我们查看scipy.misc.imresize 的旧文档页面:
-
arr 是图像本身作为 NumPy 数组。
-
size可以
-
int(表示某个百分比),
-
float(表示某个分数,这是您的示例),或者
-
tuple(表示目标大小)。
-
interp 是要使用的插值方法。
现在,让我们检查一下PIL.Image.resize 的能力:
-
size 必须是 tuple。因此,在使用上述百分比或分数时,您需要事先确定目标大小。
-
resample是重采样滤波器,基本上就是上面给出的插值方法。
这就是派生正确代码所需要知道的全部内容:
from imageio import imread # scipy.misc.imread is deprecated
import numpy as np
from PIL import Image # scipy.misc.imresize is deprecated
# Read image, get width and height
img = imread('path/to/your/image.png')
h, w = img.shape[:2]
print(img.shape)
# (241, 300, 3)
# Fraction as float
fraction = 0.2
img_resized = np.array(Image.fromarray(img).resize((int(fraction * w),
int(fraction * h)),
Image.BICUBIC))
print(img_resized.shape)
# (48, 60, 3)
# Percentage as integer
percentage = 20
img_resized = np.array(Image.fromarray(img).resize((int(percentage / 100 * w),
int(percentage / 100 * h)),
Image.BICUBIC))
print(img_resized.shape)
# (48, 60, 3)
# Size as tuple
size = (60, 48)
img_resized = np.array(Image.fromarray(img).resize(size, Image.BICUBIC))
print(img_resized.shape)
# (48, 60, 3)
该示例显示了如何处理三种不同的缩放方式(百分比、分数、目标大小)。对于不同的插值方法,您只需要从nearest 映射到PIL.Image.NEAREST,等等。
编辑:只是为了进一步解释:PIL.Image.fromarray 将输入 NumPy 数组转换为 Pillow PIL.Image.Image 对象,这样您就可以使用 PIL.Image.resize。
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.9.1
PyCharm: 2021.1.1
imageio: 2.9.0
NumPy: 1.20.2
Pillow: 8.2.0
----------------------------------------