python - numpy.pad 添加的填充量是声明的两倍

标签 python python-3.x numpy

我正在尝试填充一个 2d numpy 数组,使其达到我正在处理的图像的大小,但 np.pad功能填充是我请求的填充的两倍:

import numpy as np

gaussian = [
    [0.003, 0.013, 0.022, 0.013, 0.003],
    [0.013, 0.059, 0.097, 0.059, 0.013],
    [0.022, 0.097, 0.159, 0.097, 0.022],
    [0.013, 0.059, 0.097, 0.059, 0.013],
    [0.003, 0.013, 0.022, 0.013, 0.003]
]

gaussian = np.pad(gaussian, ((2, 2), (2, 2)), 'constant')

理想情况下,上述代码应输出 (7, 7)数组(至少这是我所期望的),但我得到的输出为 (9, 9)二维数组。

最佳答案

您的代码的行为与 documentation 完全相同表示会的。特别是,第二个参数为:

pad_width : {sequence, array_like, int}

Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.

因此,您需要使用 ((2, 2), (2, 2)) 在数组的每一侧的每个维度上添加两个附加元素。 2 + 5 + 2 = 9,正如预期的那样。

可产生 7x7 输出数组的 pad_width 有效选项示例为

  • 1
  • (1,)
  • ((0, 2),)
  • ((2, 0), (1, 1))

如果您希望填充对称,您可能需要前两个中的任何一个。

关于python - numpy.pad 添加的填充量是声明的两倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54622298/

相关文章:

Python 使用 Format 方法格式化 ASCII 转义序列

python - 在Python中,如何获取模块内文件目录的路径

python - Vim - 如何在 python shell 中运行当前的 python3 文件?

python - 在哪里可以找到 Python 的 GUI 设计器?

python - 如何从 json 更新 Mongoengine DynamicDocument

python - 二进制 numpy 数组到整数列表?

python - 如何在 Python 中使用具有 'None' 值的 numpy?

python - 按日期和总和列分组

python - 运行 ChromeDriver 的多个实例

python - babelize_shell() 在 NLTK 包中不起作用