Python:通过非整数因子下采样2D numpy数组

Max*_*aev 6 python numpy image-processing

我需要通过非整数因子(例如100x100阵列到45x45阵列)对2D numpy数组进行下采样,执行局部平均,就像Photoshop/gimp会为图像做的那样.我需要双精度.目前的选择不能很好.

  • scipy.ndimage.zoom不执行平均,并且基本上使用最近邻居采样(参见上一个问题scipy.ndimage.interpolation.zoom使用最接近邻居的算法进行缩小)

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

  • skimage.transform.rescale也使用最近邻居并转发你skimage.transform.downscale_local_mean进行局部平均,

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

我错过了其他选择吗?

Max*_*aev 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
Run Code Online (Sandbox Code Playgroud)