我有一个numpy数组,表示3D模型中面部的邻接。通常,第n行和列表示模型的第n个面。如果1位于矩阵的右上三角形中,则表示两个面之间的凸起连接。如果1位于左下角三角形中,则表示凹形连接。
例如,在下面的矩阵中,在面1和2,1和3,2和3之间存在凸起连接,依此类推。
1 2 3 4 5 6
1 [[ 0. 1. 1. 0. 0. 0.]
2 [ 0. 0. 1. 1. 1. 1.]
3 [ 0. 0. 0. 0. 0. 0.]
4 [ 0. 0. 0. 0. 1. 0.]
5 [ 0. 0. 0. 0. 0. 0.]
6 [ 0. 0. 0. 0. 0. 0.]]
我希望能够记录每张脸有多少凹凸连接。
即。面1具有:0凹面和2个凸面连接
甚至可以记录他们所连接的面孔。
即。面1具有:0凹面和2凸面(2,3)连接
到目前为止,我已尝试使用np.nonzero()
返回1的索引。但是,这会以一种似乎不太容易使用的格式返回索引(行和列索引的单独数组:
(array([ 0, 0, 1, 1, 1, 1, 3]), array([ 1, 2, 2, 3, 4, 5,
4]))
任何人都可以帮助我更简单地执行此任务吗?谢谢
答案 0 :(得分:1)
试试这个:
import numpy as np
a=np.matrix([[0,1,1,0,0,0],
[ 0,0,1,1,1,1],
[ 0,0,0,0,0,0],
[ 0,0,0,0,1,0],
[ 0,0,0,0,0,0],
[ 0,0,0,0,0,0]]).astype(float)
concave={}
convex={}
for i,j in zip(np.nonzero(a)[0]+1,np.nonzero(a)[1]+1):
if j > i :
if i not in convex.keys():
convex[i]=[]
if j not in convex.keys():
convex[j]=[]
convex[i].append(j)
convex[j].append(i)
else :
if i not in concave.keys():
concave[i]=[]
if j not in concave.keys():
concave[j]=[]
concave[i].append(j)
concave[j].append(i)
print 'concave relations : {} and number of relations is {}'.format(concave,sum(len(v) for v in concave.values()))
print 'convex relations : {} and number of relations is {}'.format(convex,sum(len(v) for v in convex.values()))
给出了结果:
凹关系:{}和关系数是0
凸关系:{1:[2,3],2:[1,3,4,5,6],3:[1,2],4:[2,5],5:[2, 4],6:[2]}和关系数是14
其中字典键是面部的名称,键值是它的连接。
逻辑是:
每个非零对(i,j)
答案 1 :(得分:0)
import numpy as np
A = np.array([[0, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
convex = np.triu(A, 1) # upper triangle
concave = np.tril(A, -1) # lower triangle
convex_indices = list(zip(np.nonzero(convex)[0] + 1, np.nonzero(convex)[1] + 1))
concave_indices = list(zip(np.nonzero(concave)[0] + 1, np.nonzero(concave)[1] + 1))
num_convex = len(convex_indices)
num_concave = len(concave_indices)
print('There are {} convex connections between faces: {}'.format(num_convex, ', '.join(str(e) for e in convex_indices)))
print('There are {} concave connections between faces: {}'.format(num_concave, ', '.join(str(e) for e in concave_indices)))
# will print:
# There are 7 convex connections between faces: (1, 2), (1, 3), (2, 3), (2, 4), (2, 5), (2, 6), (4, 5)
# There are 0 concave connections between faces: