【问题标题】:Compressing RGB images with numpy用 numpy 压缩 RGB 图像
【发布时间】:2019-09-18 13:07:23
【问题描述】:

我在大小为 (10000, 32, 32, 3) 的 ndarray 中有 10,000 个 RGB 图像。 我想使用numpy 有效地将图像(采用颜色)压缩为 2x2、4x4 等。到目前为止,我唯一的想法是手动拆分图像,压缩并将循环中的各个部分放在一起。有没有更优雅的解决方案?

【问题讨论】:

  • 认为你可以用scipy.ndimage.mean做你想做的事
  • 如果我了解您想要做什么(仅调整尺寸 1 和 2 中的图像大小),那么 scipy.ndimage.zoom() 允许您在不同尺寸上使用不同的比例因子。
  • 所以您希望输出形状为 (10000, 8, 8, 3) 以进行 4x4 插值?

标签: python-3.x numpy image-processing rgb


【解决方案1】:

你可以这样做,使用scipy.ndimage.zoom:

import numpy as np
import scipy.ndimage as si

def resample(img, dims):
    orig = img.shape[1]

    new_imgs = []
    for dim in dims:
        factor = dim / orig
        new_img = si.zoom(img, zoom=[1, factor, factor, 1])
        new_imgs.append(new_img)

    return new_imgs

例如,随机数据:

>>> 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)]

请注意(下面)的注释,您可能需要调整 zoom 函数中的 mode 参数。

【讨论】:

  • 代码正是我需要的。但是,我注意到 si.zoom 函数与 dims = 16 会产生不同的结果。由于某种原因,两个边缘上的像素变为黑色。我将mode 参数设置为“最近”,它解决了问题。
【解决方案2】:

您可以使用 SciKit 图片的view_as_blocksnp.mean()

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)

【讨论】:

    猜你喜欢
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 2019-08-06
    • 2020-02-29
    • 1970-01-01
    • 2013-08-07
    相关资源
    最近更新 更多