有效调整np.array图像批次的大小

Aus*_*tin 5 python image-resizing python-3.x scikit-image tensorflow

我有一个4D np.array大小(10000,32,32,3),代表一组10000个RGB图像。

如何使用skimage.transform.resize或其他功能有效地调整所有图像的大小,以便将(32,32)插值到(224,224)?我更喜欢使用skimage进行此操作,但是我愿意接受任何不使用的解决方案tf.image.resize_images

我当前的解决方案正在使用tf.image.resize_images,但稍后会在我的管道中导致GPU内存问题(在jupyter笔记本中完成后不会释放内存),所以我想更换它。

例:

import tensorflow as tf
X = tf.image.resize_images(X,[224, 224])
with tf.Session() as sess:
    X = X.eval()
Run Code Online (Sandbox Code Playgroud)

Aus*_*tin 6

我不太可能接受我自己的答案,但似乎一个简单的 for 循环实际上相当快(说 ~300% cpu 利用率来自top)。

from skimage.transform import resize

imgs_in = np.random.rand(100, 32, 32, 3)
imgs_out = np.zeros((100,224,224,3))

for n,i in enumerate(imgs_in):
    imgs_out[n,:,:,:] = resize(imgs_in[n,:,:,:], imgs_out.shape[1:], anti_aliasing=True)

print(imgs_out.shape)
Run Code Online (Sandbox Code Playgroud)

似乎比ndi.zoom我的机器快 7-8 倍。multiprocessing我认为尝试将其进一步并行化会更好。


And*_*eak 3

一种可能性是scipy.ndimage.zoom它可以与您的图像集合一起使用,并使用给定顺序的样条插值来对图像进行上采样:

import numpy as np
import scipy.ndimage as ndi

imgs_in = np.random.rand(100, 32, 32, 3)
factor = 224/imgs_in.shape[1]
imgs_out = ndi.zoom(imgs_in, (1, factor, factor, 1), order=2)
print(imgs_out.shape)
Run Code Online (Sandbox Code Playgroud)

最终的形状(100, 224, 224, 3)符合预期。

您必须检查运行时间和结果是否满足您的需求。调整插值顺序可能会影响这一点:二阶样条曲线和(默认)三阶样条曲线之间存在明显的速度差异,但代价是插值质量。

  • 这难道不适合“joblib”或多线程/多处理 10,000 张图像吗? (2认同)