image - 如何使用 imageio 调整图像大小?

标签 image python-imaging-library numpy-ndarray python-imageio

考虑一张图片 img类型 imageio.core.util.Array .img的形状是 (256, 256, 3) .我想将其调整为 (128, 128, 3) .
我至少尝试了以下三个:

img.resize(img_res, pilmode="RGB")
img.resize(img_res)
img = cv2.resize(img, self.img_res)
这里img_res = (128, 128) .
他们没有一个工作得很好。如何将我的图像调整到所需的大小?

最佳答案

根据documentation on imageio.core.util.Array , Array是“np.ndarray [...] 的子类”。因此,当调用 resize 时关于一些 img类型 Array , 实际调用转到 np.ndarray.resize – 其中不是 np.resize !这在这里很重要。
来自 np.ndarray.resize 的文档:

Raises:

ValueError

If a does not own its own data [...]


这就是为什么,一些代码像
import imageio

img = imageio.imread('path/to/your/image.png')
img.resize((128, 128))
会以这种方式失败:
Traceback (most recent call last):
    img.resize((128, 128))
ValueError: cannot resize this array: it does not own its data
该错误似乎与 Array 有关类,因为以下代码也失败并显示相同的错误消息:
from imageio.core.util import Array
import numpy as np

img = Array(np.zeros((200, 200, 3), np.uint8))
img.resize((128, 128))
显然,Array类只存储一些不能直接访问的 NumPy 数组的 View ,也许是一些内部内存缓冲区!?
现在,让我们看看可能的解决方法:
实际上,使用 np.resize喜欢
import imageio
import numpy as np

img = imageio.imread('path/to/your/image.png')
img = np.resize(img, (128, 128, 3))
不是一个好的选择,因为np.resize并非旨在正确调整图像大小。所以,结果是扭曲的。
使用 OpenCV 对我来说很好用:
import cv2
import imageio

img = imageio.imread('path/to/your/image.png')
img = cv2.resize(img, (128, 128))
请记住,OpenCV 使用 BGR 排序,而 imageio 使用 RGB 排序——这在使用 cv2.imshow 时也很重要。例如。
使用 Pillow 也没有问题:
import imageio
from PIL import Image

img = imageio.imread('path/to/your/image.png')
img = Image.fromarray(img).resize((128, 128))
最后,还有skimage.transform.resize :
import imageio
from skimage.transform import resize

img = imageio.imread('path/tp/your/image.png')
img = resize(img, (128, 128))
选择最适合您需求的一款!
----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.8.5
imageio:       2.9.0
NumPy:         1.19.5
OpenCV:        4.5.1
Pillow:        8.1.0
scikit-image:  0.18.1
----------------------------------------

关于image - 如何使用 imageio 调整图像大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65733362/

相关文章:

python - 将 2D 数组 reshape 为 3D 数组以进行 tiff 转换

image - 生成和使用许多图像失败

html - 在 css 中使用 % 调整图像大小

ios - GPUImageSoftLightBlendFilter - 在图像 iOS 的透明区域显示黑色区域

php - 图像在移动设备上正确旋转,而不是在桌面上

python - 将opencv图像格式转换为PIL图像格式?

python - 数据类型错误

python - 使用python在单色图像中围绕 Blob 的矩形​​边界框

python-3.x - 使用 mypy 对 NumPy ndarray 进行特定类型注释

python - 属性错误 : 'numpy.ndarray' object has no attribute 'get_shape' ?