【问题标题】:Python array manipulation using numpy使用 numpy 进行 Python 数组操作
【发布时间】:2014-06-23 19:54:30
【问题描述】:

我正在尝试复制数组的边框:

A=[1,2],[3,4] 

并希望结果为

[1,1,1,2,2,2]
[1,1,1,2,2,2]
[1,1,1,2,2,2]
[3,3,3,4,4,4]
[3,3,3,4,4,4]
[3,3,3,4,4,4]

你如何在 python 中做到这一点?我正在使用

import numpy
(a,2,reflect') or wrap I am not getting this array

【问题讨论】:

  • 当你说“复制边框”时,究竟是什么意思?您的示例输入只是角落,因此它没有向我们展示边缘或内部元素应该发生什么。

标签: python image-processing numpy scipy


【解决方案1】:

您可以使用嵌套的repeat 方法(IPython 中的示例):

In [1]: import numpy as np

In [2]: A = np.array([[1,2],[3,4]])

In [3]: A.repeat(3, 1).repeat(3, 0)
Out[3]: 
array([[1, 1, 1, 2, 2, 2],
       [1, 1, 1, 2, 2, 2],
       [1, 1, 1, 2, 2, 2],
       [3, 3, 3, 4, 4, 4],
       [3, 3, 3, 4, 4, 4],
       [3, 3, 3, 4, 4, 4]])

但是对于图像处理,您可能想看看例如:

尤其是 ImageMagick 提供了很多图像处理工具。

【讨论】:

  • 还有一个repeat 方法,它可能更具可读性。
【解决方案2】:

如果你有 numpy 1.7 或更高版本,你可以使用np.pad,和mode='edge'

In [8]: a
Out[8]: 
array([[1, 2],
       [3, 4]])

In [9]: np.pad(a, pad_width=2, mode='edge')
Out[9]: 
array([[1, 1, 1, 2, 2, 2],
       [1, 1, 1, 2, 2, 2],
       [1, 1, 1, 2, 2, 2],
       [3, 3, 3, 4, 4, 4],
       [3, 3, 3, 4, 4, 4],
       [3, 3, 3, 4, 4, 4]])

【讨论】:

  • 这与另一个答案完全不同,但就问题的当前状态而言,很难判断其中一个答案是否正确,如果有的话,哪个是正确的。
猜你喜欢
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
相关资源
最近更新 更多