【问题标题】:Python: downsample 2D numpy array by a non-integer factorPython:通过非整数因子对 2D numpy 数组进行下采样
【发布时间】:2016-03-11 08:57:49
【问题描述】:

我需要以执行局部平均的方式按非整数因子(例如 100x100 数组到 45x45 数组)对 2D numpy 数组进行下采样,就像 Photoshop/gimp 对图像执行此操作一样。我需要双精度。目前的选择不能很好地做到这一点。

  • scipy.ndimage.zoom不进行平均,基本使用 最近邻采样(参见上一个问题scipy.ndimage.interpolation.zoom uses nearest-neighbor-like algorithm for scaling-down

  • scipy.misc.imresize 将数组转换为 int8;我需要更多 精度和浮点数

  • skimage.transform.rescale 也使用最近邻并将您转发到skimage.transform.downscale_local_mean 进行本地平均,

  • skimage.transform.downscale_local_mean 只能执行整数缩放因子(如果因子为非整数,则用零填充图像)。整数比例因子是一个微不足道的 numpy excersice。

我是否错过了其他选择?

【问题讨论】:

  • 不是最优雅的,我不确定这里的数学,但如果你只是想要一些有用的东西,我会把它放大 9 (900X900) 然后缩小 20 (45X45) 所以你可以在两个步骤中按整数进行缩放
  • 我目前正在使用放大到最终大小的最近乘数(在这种情况下为 135),然后通过块平均来缩小。它有效,但有点丑陋,尤其是对于巨大的矩阵。

标签: python numpy image-processing


【解决方案1】:

我最终编写了一个小函数,使用scipy.ndimage.zoom 放大图像,但要缩小它首先将其放大为原始形状的倍数,然后通过块平均缩小。它接受 scipy.zoom 的任何其他关键字参数(orderprefilter

我仍在寻找使用可用软件包的更清洁的解决方案。

def zoomArray(inArray, finalShape, sameSum=False, **zoomKwargs):
    inArray = np.asarray(inArray, dtype = np.double)
    inShape = inArray.shape
    assert len(inShape) == len(finalShape)
    mults = []
    for i in range(len(inShape)):
        if finalShape[i] < inShape[i]:
            mults.append(int(np.ceil(inShape[i]/finalShape[i])))
        else:
            mults.append(1)
    tempShape = tuple([i * j for i,j in zip(finalShape, mults)])

    zoomMultipliers = np.array(tempShape) / np.array(inShape) + 0.0000001
    rescaled = zoom(inArray, zoomMultipliers, **zoomKwargs)

    for ind, mult in enumerate(mults):
        if mult != 1:
            sh = list(rescaled.shape)
            assert sh[ind] % mult == 0
            newshape = sh[:ind] + [sh[ind] / mult, mult] + sh[ind+1:]
            rescaled.shape = newshape
            rescaled = np.mean(rescaled, axis = ind+1)
    assert rescaled.shape == finalShape

    if sameSum:
        extraSize = np.prod(finalShape) / np.prod(inShape)
        rescaled /= extraSize
    return rescaled

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-17
    • 2017-12-19
    • 2019-04-17
    • 2015-10-27
    • 2012-06-06
    • 2017-06-12
    • 2019-10-27
    • 1970-01-01
    相关资源
    最近更新 更多