如何获得所有阵列边缘? [英] How to get all array edges?

查看:79
本文介绍了如何获得所有阵列边缘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个n x n数组,想接收它的轮廓值.例如,

I have a n x n array, and want to receive its outline values. For example,

[4,5,6,7]

[2 ,2,6, 3]

[4 ,4、9, 4]

[8,1,6,1]

从这个我会得到这个

[4,5,6,7,3,4,1,6,1,8,4,2]

(请参阅粗体显示位置)

(see where bold)

因此,从本质上讲,获取围绕2D数组边缘的所有值的1D数组的最效率方法是什么? 我问是因为我假设有一个numPy函数可以解决这个问题(我还没有找到它!),而不是通过循环手动完成?

So essentially, what is the most efficient way of getting a 1D array of all the values going around the edges of a 2D array? I ask because I assume there is a numPy function that helps with this (which I haven't yet found!), instead of doing it manually with loops?

推荐答案

In [1]: arr=np.arange(16).reshape(4,4)
In [2]: arr
Out[2]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

一个相对简单的方法-按顺时针顺序是:

A relatively straight forward way of doing this - in clockwise order is:

In [5]: alist=[arr[0,:-1], arr[:-1,-1], arr[-1,::-1], arr[-2:0:-1,0]]
In [6]: alist
Out[6]: [array([0, 1, 2]), array([ 3,  7, 11]), array([15, 14, 13, 12]), array([8, 4])]
In [7]: np.concatenate(alist)
Out[7]: array([ 0,  1,  2,  3,  7, 11, 15, 14, 13, 12,  8,  4])

从某种意义上讲,这是一个循环,因为我必须构建4个切片.但是,如果4与n相比较小,则价格不菲.它必须在某种程度上串联.

In a sense it's a loop, in that I have to build 4 slices. But if 4 is small compared to n, that's a small price. It has to concatenate at some level.

如果顺序无关紧要,我们可以将切片简化一些(例如,忘记相反的顺序,等等).

If order doesn't matter we could simplify the slices some (e.g. forgetting the reverse order, etc).

alist=[arr[0,:], arr[1:,-1], arr[-1,:-1], arr[1:-1,0]]

如果我不在乎顺序,或者不愿重复计算角落,我可以使用:

If I didn't care about order, or double counting the corners I could use:

np.array([arr[[0,n],:], arr[:,[0,n]].T]).ravel()

消除重复的角点

In [18]: np.concatenate((arr[[0,n],:].ravel(), arr[1:-1,[0,n]].ravel()))
Out[18]: array([ 0,  1,  2,  3, 12, 13, 14, 15,  4,  7,  8, 11])

这篇关于如何获得所有阵列边缘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆