Python: 降采样2D numpy数组通过非整数

2024-09-26 17:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要以执行局部平均的方式将2D numpy数组的非整数因子(例如100x100数组降到45x45数组),就像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过度。

我错过了其他的选择吗?在


Tags: 图像numpylocal精度transform局部整数scipy
1条回答
网友
1楼 · 发布于 2024-09-26 17:44:44

我最后编写了一个小函数,它使用scipy.ndimage.zoom对图像进行放大,但是对于缩小尺寸,它首先将其放大为原始形状的倍数,然后通过块平均缩小比例。它接受scipy.zoomorderprefilter)的任何其他关键字参数

我仍然在寻找一个更干净的解决方案使用可用的软件包。在

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

相关问题 更多 >

    热门问题