Home > Software design >  Python - Method to get the array around an slice in a matrix
Python - Method to get the array around an slice in a matrix

Time:09-18

I define a Matrix NxN, with random values(0,1). I need to get the sum of the digits around the consecutive 1's.

For example:

100110001
101001000
100001001
000000000
000111001
000000100
.. ..

For 111 in the above, the sum of the surrounding digits is 1.

Is there some way using numpy or itertools or anything to get the sum or the array of the digits around?? Please help, cheers

For detecting random consecutives 1's i use:

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])))

And to get the index of 1s :

idx =[idx for idx, i in enumerate(matrix[4]) if i == 1]

CodePudding user response:

This might not fully answer your question, but it might point you in the right direction :

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

  • Related