Python 3.x 用numpy压缩RGB图像

Python 3.x 用numpy压缩RGB图像,python-3.x,numpy,image-processing,rgb,Python 3.x,Numpy,Image Processing,Rgb,我有10000张RGB格式的图像,大小为(10000,32,32,3)。 我想使用numpy有效地将图像压缩到2x2、4x4等。到目前为止,我唯一的想法是手动分割图像,压缩图像,然后在循环中把这些片段放在一起。有更优雅的解决方案吗?您可以使用以下方法执行类似操作: 例如,对于随机数据: >>> img = np.random.random((100, 32, 32, 3)) >>> resample(img, dims = [2, 4, 8, 16, 32])

我有10000张RGB格式的图像,大小为(10000,32,32,3)。
我想使用
numpy
有效地将图像压缩到2x2、4x4等。到目前为止,我唯一的想法是手动分割图像,压缩图像,然后在循环中把这些片段放在一起。有更优雅的解决方案吗?

您可以使用以下方法执行类似操作:

例如,对于随机数据:

>>> img = np.random.random((100, 32, 32, 3))
>>> resample(img, dims = [2, 4, 8, 16, 32])
>>> [img.shape for img in new_imgs]
[(100, 2, 2, 3),
(100, 4, 4, 3),
(100, 8, 8, 3),
(100, 16, 16, 3),
(100, 32, 32, 3)]

从下面的注释中注意到,您可能需要调整
缩放
功能中的
模式
参数。

您可以使用SciKit image的
视图作为块
np.mean()


我想你可以用
scipy.ndimage.mean做你想做的事情
如果我了解你想做什么(只在维度1和维度2中调整图像大小),那么
scipy.ndimage.zoom()
允许你在不同维度上使用不同的比例因子。因此你希望输出形状是
(10000,8,3)
对于4x4插值?代码正是我需要的。然而,我注意到
si.zoom
函数与
dims=16
产生不同的结果。由于某种原因,两条边上的像素变为黑色。我将
模式
参数设置为“最近”,解决了问题。
>>> img = np.random.random((100, 32, 32, 3))
>>> resample(img, dims = [2, 4, 8, 16, 32])
>>> [img.shape for img in new_imgs]
[(100, 2, 2, 3),
(100, 4, 4, 3),
(100, 8, 8, 3),
(100, 16, 16, 3),
(100, 32, 32, 3)]
import numpy as np
import skimage

images = np.random.rand(10000, 32, 32, 3)
images_rescaled = skimage.util.view_as_blocks(images, (1, 4, 4, 1)).mean(axis=(-2, -3)).squeeze()
images_rescaled.shape
# (10000, 8, 8, 3)