Issue
I have an array like:
import numpy as np
data=np.array([[0,0,0,1,1,1,0,0,0,0,1,1,1,1,1],
[0,0,0,1,0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0]])
Requirement:
Needs to count the number of ones in an array, I can count by using this function.
print(np.count_nonzero(data==1))
the output I got:
11
But, one special requirement is needed, like if consecutive ones are more than 3 times then only count the ones, in that case, the excepted count of number ones more than 3 consecutive are 5
expected output:
5
Solution
You can erode/dilate your data to remove the stretches of less than N consecutive 1s.
from scipy.ndimage import binary_erosion, binary_dilation
N = 3
k = np.ones((1, N+1))
binary_dilation(binary_erosion(data, k), k).sum()
Output: 5
Output on data=np.array([[0,0,0,1,1,1,0,0,0,0,1,1,1,1,1], [0,0,0,1,1,1,1,1,1,1,1,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0]])
: 13
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.