Suppose one has a numpy array of floats where all values are in [0,1]
e.g.
arr = np.array([
[0.1, 0.1, 0.1, 0.4, 0.91, 0.81, 0.84], # channel 1
[0.81, 0.79, 0.85, 0.1, 0.2, 0.61, 0.91], # channel 2
[0.3, 0.1, 0.24, 0.87, 0.62, 1, 0 ], # channel 3
#...
])
and that one wants to covert this into a binary array. This can be easily done with a cutoff with:
def binary_mask(arr, cutoff=0.5):
return (arr > cutoff).astype(int)
m = binary_mask(arr)
# array([[0, 0, 0, 0, 1, 1, 1],
# [1, 1, 1, 0, 0, 1, 1],
# [0, 0, 0, 1, 1, 1, 0]])
one can get all the indices of the 1
s via
for channel in m:
print(channel.nonzero())
# (array([4, 5, 6]),)
# (array([0, 1, 2, 5, 6]),)
# (array([3, 4, 5]),)
what would be a performant way to the consecutive runs of numbers
e.g.
[
[[4,6]],
[[0,2], [5,6]],
[[3,5]]
]
a naive approach might be:
def consecutive_integers(arr):
# indexes of nonzero
nz = arr.nonzero()[0]
# storage of "runs"
runs = []
# error handle all zero array
if not len(nz):
return [[]]
# run starts with current value
run_start = nz[0]
for i in range(len(nz)-1):
# if run is broken
if nz[i]+1 != nz[i+1]:
# store run
runs.append([run_start, nz[i]])
# start next run at next number
run_start = nz[i+1]
# last run ends with last value
runs.append([run_start, nz[-1]])
return runs
print(m)
for runs in [consecutive_integers(c) for c in m]:
print(runs)
# [[0 0 0 0 1 1 1]
# [1 1 1 0 0 1 1]
# [0 0 0 1 1 1 0]]
#
# [[4, 6]]
# [[0, 2], [5, 6]]
# [[3, 5]]