【问题标题】:python numpy roll with padding in arbitrary directionpython numpy roll 与任意方向的填充
【发布时间】:2017-12-11 23:23:54
【问题描述】:

我正在尝试将一组类似图像的数据重新居中,其中我知道 x 和 y 维度中的适当偏移量。与this 问题类似,我想做类似“滚动”的操作,但不是假设周期性边界条件,而是想用零填充数组中的“空”位置。

我的问题比我链接的问题更笼统,因为我想在任意方向移动数组。在公认的解决方案中,必须始终知道图像滚动的方向,以便切断适当的边缘。特别是,这里是公认的解决方案,它涉及将数组 x 移动 1。

import numpy as np
x = np.array([[1, 2, 3],[4, 5, 6]])

print np.pad(x,((0,0),(1,0)), mode='constant')[:, :-1]

但是要进行反向操作,则必须对以下更改进行硬编码:

import numpy as np
x = np.array([[1, 2, 3],[4, 5, 6]])

print np.pad(x,((0,0),(0,1)), mode='constant')[:, 1:] 
// changed argument of pad
// and array indices

有没有一种简单的方法可以同时实现两者?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    您的modepad 的核心是:

    newmat = narray.copy()
    
    # API preserved, but completely new algorithm which pads by building the
    # entire block to pad before/after `arr` with in one step, for each axis.
    if mode == 'constant':
        for axis, ((pad_before, pad_after), (before_val, after_val)) \
                in enumerate(zip(pad_width, kwargs['constant_values'])):
            newmat = _prepend_const(newmat, pad_before, before_val, axis)
            newmat = _append_const(newmat, pad_after, after_val, axis)
    

    所以是 pad_width 元组(元组中的)决定了操作,无论是前置还是附加常量填充。请注意,它在轴上进行迭代。

    您自己的代码可能会同样快,因为 pad 在这里没有做任何神奇的事情(或编译)。

    prepend 函数执行如下连接:

    np.concatenate((np.zeros(padshape, dtype=arr.dtype), arr),
                              axis=axis)
    

    详情请见np.lib.arraypad.py

    因此,对于每个非零填充量,它都会连接到所需形状的零块上。


    In [280]: x = np.array([[1, 2, 3],[4, 5, 6]])
    

    您的两个pad 版本:

    In [281]: np.pad(x,((0,0),(1,0)), mode='constant')[:, :-1]
    Out[281]: 
    array([[0, 1, 2],
           [0, 4, 5]])
    In [282]:  np.pad(x,((0,0),(0,1)), mode='constant')[:, 1:]
    Out[282]: 
    array([[2, 3, 0],
           [5, 6, 0]])
    

    直接insert 等价物:

    In [283]: res = np.zeros_like(x)
    In [284]: res[:,1:] = x[:,:-1]
    In [285]: res
    Out[285]: 
    array([[0, 1, 2],
           [0, 4, 5]])
    In [286]: res = np.zeros_like(x)
    In [287]: res[:,:-1] = x[:,1:]
    In [288]: res
    Out[288]: 
    array([[2, 3, 0],
           [5, 6, 0]])
    

    你可以在第一个轴上做同样的事情。一般表达式为

    res = np.zeros_like(x)
    idx1 = (slice(...), slice(...))
    idx2 = (slice(...), slice(...))
    res[idx1] = x[idx2]
    

    idx 元组取决于滚动轴和方向。

    例如

    idx1 = (slice(None), slice(1,None))
    idx2 = (slice(None), slice(None,-1))
    

    2轴2方向,即4对。

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多