【问题标题】:How to resize N-d numpy image?如何调整 N-d numpy 图像的大小?
【发布时间】:2017-10-19 18:45:44
【问题描述】:

如何调整 N-d numpy 图像的大小?

我不只是想对其进行二次采样,而是对像素进行插值/平均。

例如,如果我从

array([[[3, 1, 3, 1],
        [3, 1, 3, 1],
        [3, 1, 3, 1],
        [3, 1, 3, 1]],

       [[3, 1, 3, 1],
        [3, 1, 3, 1],
        [3, 1, 3, 1],
        [3, 1, 3, 1]]], dtype=uint8)

并在所有维度上将其缩小 2 倍,我希望输出为

array([[[2, 2],
        [2, 2]]], dtype=uint8)

尝试的解决方案:

A. SciPy ndimage:

>>> scipy.ndimage.interpolation.zoom(x, .5, mode='nearest')

array([[[3, 1],
        [3, 1]]], dtype=uint8)

(可选的order参数没有区别)

B.循环 2**3 可能的偏移量:丑陋、缓慢、仅适用于整数缩放因子,并且需要额外的步骤以避免溢出。

C. OpenCV 和 PIL 仅适用于 2D 图像。

【问题讨论】:

    标签: python numpy scipy ndimage


    【解决方案1】:

    重新整形以将每个轴分成一个长度为2 的轴,给我们一个6D 数组,然后沿着后面的那些轴获得平均值(轴:1,3,5)-

    m,n,r = a.shape
    out = a.reshape(m//2,2,n//2,2,r//2,2).mean((1,3,5))
    

    扩展到n-dim数组,就是-

    def shrink(a, S=2): # S : shrink factor
        new_shp = np.vstack((np.array(a.shape)//S,[S]*a.ndim)).ravel('F')
        return a.reshape(new_shp).mean(tuple(1+2*np.arange(a.ndim)))
    

    示例运行 -

    In [407]: a
    Out[407]: 
    array([[[1, 5, 8, 2],
            [5, 6, 4, 0],
            [8, 5, 5, 5],
            [1, 0, 0, 0]],
    
           [[0, 0, 7, 6],
            [3, 5, 4, 3],
            [4, 5, 1, 3],
            [6, 7, 4, 0]]])
    
    In [408]: a[:2,:2,:2].mean()
    Out[408]: 3.125
    
    In [409]: a[:2,:2,2:4].mean()
    Out[409]: 4.25
    
    In [410]: a[:2,2:4,:2].mean()
    Out[410]: 4.5
    
    In [411]: a[:2,2:4,2:4].mean()
    Out[411]: 2.25
    
    In [412]: shrink(a, S=2)
    Out[412]: 
    array([[[ 3.125,  4.25 ],
            [ 4.5  ,  2.25 ]]])
    

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 2021-04-21
      • 2018-06-15
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 2020-01-26
      相关资源
      最近更新 更多