[英]Python - Method to get the array around an slice in a matrix
我用隨機值(0,1)定義了一個矩陣 NxN。 我需要得到圍繞連續 1 的數字的總和。
例如:
100110001
101001000
100001001
000000000
000111001
000000100
.. ..
對於上面的 111,周圍的數字之和為 1。
有沒有辦法使用numpy或itertools或任何東西來獲得數字的總和或數組? 請幫忙,加油
為了檢測隨機連續 1,我使用:
from itertools import groupby
def groups(l):
return [sum(g) for i, g in groupby(l) if i == 1]
con += list(filter(lambda x: x > 1,groups(matrix[4])))
並獲得 1s 的索引:
idx+=[idx for idx, i in enumerate(matrix[4]) if i == 1]
這可能無法完全回答您的問題,但可能會為您指明正確的方向:
In [1]: import numpy as np
In [2]: from scipy import ndimage as nd
In [3]: mat = np.random.randint(0,2,(6,6))
In [4]: mat
Out[4]:
array([[1, 1, 1, 0, 1, 1],
[1, 1, 0, 0, 1, 0],
[1, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 1, 0],
[1, 0, 0, 1, 1, 1]])
In [5]: s = np.array([[0,0,0],[1,1,1],[0,0,0]])
In [6]: lab, nlab = nd.label(mat, s)
In [7]: lab
Out[7]:
array([[ 1, 1, 1, 0, 2, 2],
[ 3, 3, 0, 0, 4, 0],
[ 5, 0, 6, 6, 6, 6],
[ 0, 0, 7, 7, 7, 0],
[ 8, 0, 9, 0, 10, 0],
[11, 0, 0, 12, 12, 12]], dtype=int32)
In [8]: s2 = nd.generate_binary_structure(2,2)
In [9]: for l in range(1, nlab+1):
...: is_l = lab==l
...: if np.sum(is_l) ==1:
...: continue
...: is_l_padded = nd.binary_dilation(is_l, s2)
...: border = np.logical_xor( is_l_padded, is_l)
...: num_ones = mat[border].sum()
...: print("label %d has %d ones around it" % (l, num_ones))
...:
label 1 has 2 ones around it
label 2 has 1 ones around it
label 3 has 5 ones around it
label 6 has 5 ones around it
label 7 has 6 ones around it
label 12 has 2 ones around it
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.